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/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
#Phix
Phix
with javascript_semantics include mpfr.e function weiferich(integer p) mpz p2pm1m1 = mpz_init() mpz_ui_pow_ui(p2pm1m1,2,p-1) mpz_sub_ui(p2pm1m1,p2pm1m1,1) return mpz_fdiv_q_ui(p2pm1m1,p2pm1m1,p*p)=0 end function printf(1,"Weiferich primes less than 5000: %V\n",{filter(get_primes_le(5000),weiferich)})
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
#PicoLisp
PicoLisp
(de **Mod (X Y N) (let M 1 (loop (when (bit? 1 Y) (setq M (% (* M X) N)) ) (T (=0 (setq Y (>> 1 Y))) M ) (setq X (% (* X X) N)) ) ) ) (let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .))) (until (> D 5000) (and (=1 (**Mod 2 (dec D) (* D D))) (println D) ) (inc 'D (++ L)) ) )
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.
#Perl
Perl
#!/usr/bin/perl -w use strict; use X11::Protocol;   my $X = X11::Protocol->new;   my $window = $X->new_rsrc; $X->CreateWindow ($window, $X->root, # parent window 'InputOutput', # class 0, # depth, copy from parent 0, # visual, copy from parent 0,0, # X,Y (window manager will override) 300,100, # width,height 0, # border width background_pixel => $X->black_pixel, event_mask => $X->pack_event_mask('Exposure', 'ButtonPress'), );   my $gc = $X->new_rsrc; $X->CreateGC ($gc, $window, foreground => $X->white_pixel);   $X->{'event_handler'} = sub { my %event = @_; my $event_name = $event{'name'};   if ($event_name eq 'Expose') { $X->PolyRectangle ($window, $gc, [ 10,10, # x,y top-left corner 30,20 ]); # width,height $X->PolyText8 ($window, $gc, 10, 55, # X,Y of text baseline [ 0, # delta X 'Hello ... click mouse button to exit.' ]);   } elsif ($event_name eq 'ButtonPress') { exit 0; } };   $X->MapWindow ($window); for (;;) { $X->handle_input; }
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.
#F.23
F#
open System.Windows.Forms   [<System.STAThread>] do Form(Text = "F# Window") |> Application.Run
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Factor
Factor
USING: ui ui.gadgets.labels ;   "This is a window..." <label> "Really?" open-window
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
#Wren
Wren
import "random" for Random import "/ioutil" for FileUtil import "/pattern" for Pattern import "/str" for Str import "/fmt" for Fmt   var dirs = [ [1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1] ] var Rows = 10 var Cols = 10 var gridSize = Rows * Cols var minWords = 25 var rand = Random.new()   class Grid { construct new() { _numAttempts = 0 _cells = List.filled(Rows, null) for (i in 0...Rows) _cells[i] = List.filled(Cols, " ") _solutions = [] }   numAttempts { _numAttempts } numAttempts=(n) { _numAttempts = n } cells { _cells } solutions { _solutions } }   var readWords = Fn.new { |fileName| var maxLen = Rows.max(Cols) var p = Pattern.new("=3/l#0%(maxLen-3)/l", Pattern.whole) return FileUtil.readLines(fileName) .map { |l| Str.lower(l.trim()) } .where { |l| p.isMatch(l) }.toList }   var placeMessage = Fn.new { |grid, msg| var p = Pattern.new("/U") var msg2 = p.replaceAll(Str.upper(msg), "") var messageLen = msg2.count if (messageLen >= 1 && messageLen < gridSize) { var gapSize = (gridSize / messageLen).floor for (i in 0...messageLen) { var pos = i * gapSize + rand.int(gapSize) grid.cells[(pos / Cols).floor][pos % Cols] = msg2[i] } return messageLen } return 0 }   var tryLocation = Fn.new { |grid, word, dir, pos| var r = (pos / Cols).floor var c = pos % Cols var len = word.count   // check bounds if ((dirs[dir][0] == 1 && (len + c) > Cols) || (dirs[dir][0] == -1 && (len - 1) > c) || (dirs[dir][1] == 1 && (len + r) > Rows) || (dirs[dir][1] == -1 && (len - 1) > r)) return 0 var overlaps = 0   // check cells var rr = r var cc = c for (i in 0...len) { if (grid.cells[rr][cc] != " " && grid.cells[rr][cc] != word[i]) return 0 cc = cc + dirs[dir][0] rr = rr + dirs[dir][1] }   // place rr = r cc = c for (i in 0...len) { if (grid.cells[rr][cc] == word[i]) { overlaps = overlaps + 1 } else { grid.cells[rr][cc] = word[i] } if (i < len - 1) { cc = cc + dirs[dir][0] rr = rr + dirs[dir][1] } }   var lettersPlaced = len - overlaps if (lettersPlaced > 0) { grid.solutions.add(Fmt.swrite("$-10s ($d,$d)($d,$d)", word, c, r, cc, rr)) } return lettersPlaced }   var tryPlaceWord = Fn.new { |grid, word| var randDir = rand.int(dirs.count) var randPos = rand.int(gridSize) for (d in 0...dirs.count) { var dir = (d + randDir) % dirs.count for (p in 0...gridSize) { var pos = (p + randPos) % gridSize var lettersPlaced = tryLocation.call(grid, word, dir, pos) if (lettersPlaced > 0) return lettersPlaced } } return 0 }   var createWordSearch = Fn.new { |words| var numAttempts = 1 var grid while (numAttempts < 100) { var outer = false grid = Grid.new() var messageLen = placeMessage.call(grid, "Rosetta Code") var target = gridSize - messageLen var cellsFilled = 0 rand.shuffle(words) for (word in words) { cellsFilled = cellsFilled + tryPlaceWord.call(grid, word) if (cellsFilled == target) { if (grid.solutions.count >= minWords) { grid.numAttempts = numAttempts outer = true break } // grid is full but we didn't pack enough words, start over break } } if (outer) break numAttempts = numAttempts + 1 } return grid }   var printResult = Fn.new { |grid| if (grid.numAttempts == 0) { System.print("No grid to display") return } var size = grid.solutions.count System.print("Attempts: %(grid.numAttempts)") System.print("Number of words: %(size)") System.print("\n 0 1 2 3 4 5 6 7 8 9") for (r in 0...Rows) { System.write("\n%(r) ") for (c in 0...Cols) System.write(" %(grid.cells[r][c]) ") } System.print("\n") var i = 0 while (i < size - 1) { System.print("%(grid.solutions[i])  %(grid.solutions[i + 1])") i = i + 2 } if (size % 2 == 1) System.print(grid.solutions[size - 1]) }   printResult.call(createWordSearch.call(readWords.call("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
#F.23
F#
open System   let LoremIpsum = " Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas varius sapien vel purus hendrerit vehicula. Integer hendrerit viverra turpis, ac sagittis arcu pharetra id. Sed dapibus enim non dui posuere sit amet rhoncus tellus consectetur. Proin blandit lacus vitae nibh tincidunt cursus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nam tincidunt purus at tortor tincidunt et aliquam dui gravida. Nulla consectetur sem vel felis vulputate et imperdiet orci pharetra. Nam vel tortor nisi. Sed eget porta tortor. Aliquam suscipit lacus vel odio faucibus tempor. Sed ipsum est, condimentum eget eleifend ac, ultricies non dui. Integer tempus, nunc sed venenatis feugiat, augue orci pellentesque risus, nec pretium lacus enim eu nibh."   let Wrap words lineWidth = let rec loop words currentWidth = seq { match (words : string list) with | word :: rest -> let (stuff, pos) = if currentWidth > 0 then if currentWidth + word.Length < lineWidth then (" ", (currentWidth + 1)) else ("\n", 0) else ("", 0) yield stuff + word yield! loop rest (pos + word.Length) | _ -> () } loop words 0   [<EntryPoint>] let main argv = for n in [72; 80] do printfn "%s" (String('-', n)) let l = Seq.toList (LoremIpsum.Split((null:char[]), StringSplitOptions.RemoveEmptyEntries)) Wrap l n |> Seq.iter (printf "%s") printfn "" 0
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
#Ruby
Ruby
wheel = "ndeokgelw" middle, wheel_size = wheel[4], wheel.size   res = File.open("unixdict.txt").each_line.select do |word| w = word.chomp next unless w.size.between?(3, wheel_size) next unless w.match?(middle) wheel.each_char{|c| w.sub!(c, "") } #sub! substitutes only the first occurrence (gsub would substitute all) w.empty? end   puts res  
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
#Transd
Transd
#lang transd   MainModule: { maxwLen: 9, minwLen: 3, dict: Vector<String>(), subWords: Vector<String>(),   procGrid: (λ grid String() cent String() subs Bool() (with cnt 0 (sort grid) (for w in dict where (and (neq (find w cent) -1) (match w "^[[:alpha:]]+$")) do (if (is-subset grid (sort (cp w))) (+= cnt 1) (if subs (append subWords w)) ) ) (ret cnt) )),   _start: (λ res 0 maxRes 0 (with fs FileStream() (open-r fs "/mnt/proj/res/unixdict.txt") (for w in (read-lines fs) where (within (size w) minwLen maxwLen) do (append dict w)) )   (lout "Main part of task:\n") (procGrid "ndeokgelw" "k" true) (lout "Number of words: " (size subWords) ";\nword list: " subWords)   (lout "\n\nOptional part of task:\n") (for w in dict where (eq (size w) maxwLen) do (for centl in (split (unique (sort (cp w))) "") do (if (>= (= res (procGrid (cp w) centl false)) maxRes) (= maxRes res) (lout "New max. number: " maxRes ", word: " w ", central letter: " centl) ) ) ) ) }
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.
#Yabasic
Yabasic
bresline = false // space toggles, for comparison   rB = 255 : gB = 255 : bB = 224 rL = 0 : gL = 0 : bL = 255   sub round(x) return int(x + .5) end sub   sub plot(x, y, c, steep) // plot the pixel at (x, y) with brightness c (where 0 <= c <= 1)   local t, C   if steep then t = x : x = y : y = t end if C = 1 - c color rL * c + rB * C, gL * c + gB * C, bL * c + bB * C   dot x, y end sub   sub plot2(x, y, f, xgap, steep) plot(x, y, (1 - f) * xgap, steep) plot(x, y + 1, f * xgap, steep) end sub   sub draw_line(x0, y0, x1, y1) local steep, t, dx, dy, gradient, xend, yend, xgap, xpxl1, ypxl1, xpxl2, ypxl2, intery   if bresline then line x0, y0, x1, y1 return end if steep = abs(y1 - y0) > abs(x1 - x0) if steep then t = x0 : x0 = y0 : y0 = t t = x1 : x1 = y1 : y1 = t end if if x0 > x1 then t = x0 : x0 = x1 : x1 = t t = y0 : y0 = y1 : y1 = t end if   dx = x1 - x0 dy = y1 - y0 if dx = 0 then gradient = 1 else gradient = dy / dx end if   // handle first endpoint xend = round(x0) yend = y0 + gradient * (xend - x0) xgap = 1 - frac(x0 + 0.5) xpxl1 = xend // this will be used in the main loop ypxl1 = int(yend) plot2(xpxl1, ypxl1, frac(yend), xgap, steep) intery = yend + gradient // first y-intersection for the main loop   // handle second endpoint xend = round(x1) yend = y1 + gradient * (xend - x1) xgap = frac(x1 + 0.5) xpxl2 = xend // this will be used in the main loop ypxl2 = int(yend) plot2(xpxl2, ypxl2, frac(yend), xgap, steep)   // main loop for x = xpxl1 + 1 to xpxl2 - 1 plot2(x, int(intery), frac(intery), 1, steep) intery = intery + gradient next x end sub   w = 640 : h = 480 open window w, h   color 0, 0, 255   draw_line(0, 0, 200, 200) draw_line(w, 0, 200, 200) draw_line(0, h, 200, 200) draw_line(w, h, 200, 200)
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.
#Nim
Nim
import xmltree, strtabs, sequtils   proc charsToXML(names, remarks: seq[string]): XmlNode = result = <>CharacterRemarks() for name, remark in items zip(names, remarks): result.add <>Character(name=name, remark.newText)   echo charsToXML(@["April", "Tam O'Shanter", "Emily"], @["Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift"])
http://rosettacode.org/wiki/XML/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.
#Objeck
Objeck
use Data.XML; use Collection.Generic;   class Test { function : Main(args : String[]) ~ Nil { # list of name names := Vector->New()<String>; names->AddBack("April"); names->AddBack("Tam O'Shanter"); names->AddBack("Emily"); # list of comments comments := Vector->New()<String>; comments->AddBack("Bubbly: I'm > Tam and <= Emily"); comments->AddBack("Burns: \"When chapman billies leave the street ...\""); comments->AddBack(XmlElement->EncodeString("Short & shrift"); # build XML document builder := XmlBuilder->New("CharacterRemarks"); root := builder->GetRoot(); if(names->Size() = comments->Size()) { each(i : names) { element := XmlElement->New(XmlElement->Type->ELEMENT, "Character"); element->AddAttribute(XmlAttribute->New("name", names->Get(i))); element->SetContent(XmlElement->EncodeString(comments->Get(i))); root->AddChild(element); }; }; builder->ToString()->PrintLine(); } }  
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
#Lua
Lua
  require 'lxp' data = [[<Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students>]]   p = lxp.new({StartElement = function (parser, name, attr) if name == 'Student' and attr.Name then print(attr.Name) end end})   p:parse(data) p:close()  
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)
#VBScript
VBScript
'Arrays - VBScript - 08/02/2021 'create a static array Dim a(3) ' 4 items : a(0), a(1), a(2), a(3) 'assign a value to elements For i = 1 To 3 a(i) = i * i Next 'and retrieve elements buf="" For i = 1 To 3 buf = buf & a(i) & " " Next WScript.Echo buf   'create a dynamic array Dim d() ReDim d(3) ' 4 items : d(0), d(1), d(2), d(3) For i = 1 To 3 d(i) = i * i Next buf="" For i = 1 To 3 buf = buf & d(i) & " " Next WScript.Echo buf   d(0) = 0 'expand the array and preserve existing values ReDim Preserve d(4) ' 5 items : d(0), d(1), d(2), d(3), d(4) d(4) = 16 buf="" For i = LBound(d) To UBound(d) buf = buf & d(i) & " " Next WScript.Echo buf   'create and initialize an array dynamicaly b = Array(1, 4, 9) 'and retrieve all elements WScript.Echo Join(b,",")   'Multi-Dimensional arrays 'The following creates a 5x4 matrix Dim mat(4,3)
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.
#Vlang
Vlang
import os const ( x = [1.0, 2, 3, 1e11] y = [1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]   xprecision = 3 yprecision = 5 )   fn main() { if x.len != y.len { println("x, y different length") return } mut f := os.create("filename")? defer { f.close() } for i,_ in x { f.write_string('${x[i]:3}, ${y[i]:1G}\n')? } }
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.
#Wren
Wren
import "io" for File import "/fmt" for Fmt   var x = [1, 2, 3, 1e11] var y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791] var xprec = 3 - 1 var yprec = 5 - 1 File.create("filename.txt") { |file| for (i in 0...x.count) { var f = (i < x.count-1) ? "h" : "e" var s = Fmt.swrite("$0.%(xprec)%(f)\t$0.%(yprec)%(f)\n", x[i], y[i]) file.writeBytes(s) } }
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.
#newLISP
newLISP
(define (status door-num) (let ((x (int (sqrt door-num)))) (if (= (* x x) door-num) (string "Door " door-num " Open") (string "Door " door-num " Closed"))))   (dolist (n (map status (sequence 1 100))) (println n))  
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
#Factor
Factor
USING: combinators.short-circuit io kernel lists lists.lazy locals math math.primes.factors prettyprint sequences ; IN: rosetta-code.weird-numbers   :: has-sum? ( n seq -- ? ) seq [ f ] [ unclip-slice :> ( xs x ) n x < [ n xs has-sum? ] [ { [ n x = ] [ n x - xs has-sum? ] [ n xs has-sum? ] } 0|| ] if ] if-empty ;   : weird? ( n -- ? ) dup divisors but-last reverse { [ sum < ] [ has-sum? not ] } 2&& ;   : weirds ( -- list ) 1 lfrom [ weird? ] lfilter ;   : weird-numbers-demo ( -- ) "First 25 weird numbers:" print 25 weirds ltake list>array . ;   MAIN: weird-numbers-demo
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
#FreeBASIC
FreeBASIC
  Function GetFactors(n As Long,r() As Long) As Long Redim r(0) r(0)=1 Dim As Long count,acc For z As Long=2 To n\2 If n Mod z=0 Then count+=1:redim preserve r(0 to count) r(count)=z acc+=z End If Next z Return 1+acc End Function   sub sumcombinations(arr() As Long,n As Long,r As Long,index As Long,_data() As Long,i As Long,Byref ans As Long,ref As Long) Dim As Long acc If index=r Then For j As Long=0 To r-1 acc+=_data(j) If acc=ref Then ans=1:Return If acc>ref then return Next j Return End If If i>=n Or ans<>0 Then Return _data(index) = arr(i) sumcombinations(arr(),n,r,index + 1,_data(),i+1,ans,ref) sumcombinations(arr(),n,r,index,_data(),i+1,ans,ref) End sub   Function IsWeird(u() As Long,num As Long) As Long Redim As Long d() Dim As Long ans For r As Long=2 To Ubound(u) Redim d(r) ans=0 sumcombinations(u(),Ubound(u)+1,r,0,d(),0,ans,num) If ans =1 Then Return 0 Next r Return 1 End Function   Redim As Long u() Dim As Long SumFactors,number=2,count Do number+=2 SumFactors=GetFactors(number,u()) If SumFactors>number Then If IsWeird(u(),number) Then Print number;" ";:count+=1 End If Loop Until count=25 Print Print "first 25 done" Sleep  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
locs = Position[ ImageData[Binarize[Rasterize["Mathematica", ImageSize -> 150]]], 0]; Print[StringRiffle[ StringJoin /@ ReplacePart[ ReplacePart[ ConstantArray[ " ", {Max[locs[[All, 1]]] + 1, Max[locs[[All, 2]]] + 1}], locs -> "\\"], Map[# + 1 &, locs, {2}] -> "#"], "\n"]];
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
#MiniScript
MiniScript
data = [ " ______ _____ _________", "|\ \/ \ ___ ________ ___|\ _____\ ________ ________ ___ ________ _________ ", "\ \ _ \ _ \|\ \|\ ___ \|\ \ \ \____||\ ____\|\ ____\|\ \|\ __ \|\___ ___\ ", " \ \ \\\__\ \ \ \ \ \ \\ \ \ \ \ \_____ \ \ \___|\ \ \___|\ \ \ \ \|\ \|___ \ \_| ", " \ \ \\|__| \ \ \ \ \ \\ \ \ \ \|____|\ \ \ \ \ \ \ \ \ \ \ ____\ \ \ \ ", " \ \ \ \ \ \ \ \ \ \\ \ \ \ \____\_\ \ \ \____\ \ \ \ \ \ \ \___| \ \ \ ", " \ \__\ \ \__\ \__\ \__\\ \__\ \__\_________\ \_______\ \__\ \ \__\ \__\ \ \__\", " \|__| \|__|\|__|\|__| \|__|\|__||________|\|_______|\|__| \|__|\|__| \|__|"]   for line in data print line end for
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++.
#BBC_BASIC
BBC BASIC
SYS "LoadLibrary", "URLMON.DLL" TO urlmon% SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF% SYS "LoadLibrary", "WININET.DLL" TO wininet% SYS "GetProcAddress", wininet%, "DeleteUrlCacheEntryA" TO DUCE%   url$ = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" file$ = @tmp$+"navytime.txt"   SYS DUCE%, url$ SYS UDTF%, 0, url$, file$, 0, 0 TO result% IF result% ERROR 100, "Download failed"   file% = OPENIN(file$) REPEAT text$ = GET$#file% IF INSTR(text$, "UTC") PRINT MID$(text$, 5) UNTIL EOF#file% CLOSE #file%
http://rosettacode.org/wiki/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++.
#C
C
#include <stdio.h> #include <string.h> #include <curl/curl.h> #include <sys/types.h> #include <regex.h>   #define BUFSIZE 16384   size_t lr = 0;   size_t filterit(void *ptr, size_t size, size_t nmemb, void *stream) { if ( (lr + size*nmemb) > BUFSIZE ) return BUFSIZE; memcpy(stream+lr, ptr, size*nmemb); lr += size*nmemb; return size*nmemb; }   int main() { CURL *curlHandle; char buffer[BUFSIZE]; regmatch_t amatch; regex_t cregex;   curlHandle = curl_easy_init(); curl_easy_setopt(curlHandle, CURLOPT_URL, "http://tycho.usno.navy.mil/cgi-bin/timer.pl"); curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, filterit); curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, buffer); int success = curl_easy_perform(curlHandle); curl_easy_cleanup(curlHandle);   buffer[lr] = 0;   regcomp(&cregex, " UTC", REG_NEWLINE); regexec(&cregex, buffer, 1, &amatch, 0); int bi = amatch.rm_so; while ( bi-- > 0 ) if ( memcmp(&buffer[bi], "<BR>", 4) == 0 ) break;   buffer[amatch.rm_eo] = 0;   printf("%s\n", &buffer[bi+4]);   regfree(&cregex); return 0; }
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.
#Racket
Racket
  #lang racket/gui   (define (say . xs) (printf ">>> ~a\n" (apply ~a xs)) (flush-output))   (define frame (new frame% [label "Demo"] [width 400] [height 400])) (say "frame = " frame) ; plain value   (say 'Show) (send frame show #t) (sleep 1) (say 'Hide) (send frame show #f) (sleep 1) (say 'Show) (send frame show #t) (sleep 1) (say 'Minimize) (send frame iconize #t) (sleep 1) (say 'Restore) (send frame iconize #f) (sleep 1) (say 'Maximize) (send frame maximize #t) (sleep 1) (say 'Restore) (send frame maximize #f) (sleep 1) (say 'Move) (send frame move 100 100) (sleep 1) (say 'Resize) (send frame resize 100 100) (sleep 1) (say 'Close) (send frame show #f) (sleep 1) ; that's how we close a window  
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.
#Raku
Raku
use X11::libxdo;   my $xdo = Xdo.new;   say 'Visible windows:'; printf "Class: %-21s ID#: %10d pid: %5d Name: %s\n", $_<class ID pid name> for $xdo.get-windows.sort(+*.key)».value; sleep 2;   my $id = $xdo.get-active-window;   my ($w, $h ) = $xdo.get-window-size( $id ); my ($wx, $wy) = $xdo.get-window-location( $id ); my ($dw, $dh) = $xdo.get-desktop-dimensions( 0 );   $xdo.move-window( $id, 150, 150 );   $xdo.set-window-size( $id, 350, 350, 0 );   sleep .25;   for flat 1 .. $dw - 350, $dw - 350, {$_ - 1} … 1 -> $mx { # my $my = (($mx / $dw * τ).sin * 500).abs.Int; $xdo.move-window( $id, $mx, $my ); $xdo.activate-window($id); }   sleep .25;   $xdo.move-window( $id, 150, 150 );   my $dx = $dw - 300; my $dy = $dh - 300;   $xdo.set-window-size( $id, $dx, $dy, 0 );   sleep .25;   my $s = -1;   loop { $dx += $s * ($dw / 200).ceiling; $dy += $s * ($dh / 200).ceiling; $xdo.set-window-size( $id, $dx, $dy, 0 ); $xdo.activate-window($id); sleep .005; $s *= -1 if $dy < 200; last if $dx >= $dw; }   sleep .25;   $xdo.set-window-size( $id, $w, $h, 0 ); $xdo.move-window( $id, $wx, $wy ); $xdo.activate-window($id);   sleep .25;   $xdo.minimize($id); $xdo.activate-window($id); sleep 1; $xdo.raise-window($id); sleep .25;  
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
#Batch_File
Batch File
  @echo off   call:wordCount 1 2 3 4 5 6 7 8 9 10 42 101   pause>nul exit   :wordCount setlocal enabledelayedexpansion   set word=100000 set line=0 for /f "delims=" %%i in (input.txt) do ( set /a line+=1 for %%j in (%%i) do ( if not !skip%%j!==true ( echo line !line! ^| word !word:~-5! - "%%~j"   type input.txt | find /i /c "%%~j" > count.tmp set /p tmpvar=<count.tmp   set tmpvar=000000000!tmpvar! set tmpvar=!tmpvar:~-10! set count[!word!]=!tmpvar! %%~j   set "skip%%j=true" set /a word+=1 ) ) ) del count.tmp   set wordcount=0 for /f "tokens=1,2 delims= " %%i in ('set count ^| sort /+14 /r') do ( set /a wordcount+=1 for /f "tokens=2 delims==" %%k in ("%%i") do ( set word[!wordcount!]=!wordcount!. %%j - %%k ) )   cls for %%i in (%*) do echo !word[%%i]! endlocal goto:eof    
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.
#Delphi
Delphi
  program Wireworld;   {$APPTYPE CONSOLE}   uses System.SysUtils, System.IOUtils;   var rows, cols: Integer; rx, cx: Integer; mn: TArray<Integer>;   procedure Print(grid: TArray<byte>); begin writeln(string.Create('_', cols * 2), #10);   for var r := 1 to rows do begin for var c := 1 to cols do begin if grid[r * cx + c] = 0 then write(' ') else write(' ', chr(grid[r * cx + c])); end; writeln; end; end;   procedure Step(var dst: TArray<byte>; src: TArray<byte>); begin for var r := 1 to rows do begin for var c := 1 to cols do begin var x := r * cx + c; dst[x] := src[x];   case chr(dst[x]) of 'H': dst[x] := ord('t'); 't': dst[x] := ord('.'); '.': begin var nn := 0; for var n in mn do if src[x + n] = ord('H') then inc(nn); if (nn = 1) or (nn = 2) then dst[x] := ord('H'); end; end; end; end; end;   procedure Main(); const CONFIG_FILE = 'ww.config'; begin   if not FileExists(CONFIG_FILE) then begin Writeln(CONFIG_FILE, ' not exist'); exit; end;   var srcRows := TFile.ReadAllLines(CONFIG_FILE);   rows := length(srcRows);   cols := 0; for var r in srcRows do begin if Length(r) > cols then cols := length(r); end;   rx := rows + 2; cx := cols + 2;   mn := [-cx - 1, -cx, -cx + 1, -1, 1, cx - 1, cx, cx + 1];   var _odd: TArray<byte>; var _even: TArray<byte>;   SetLength(_odd, rx * cx); SetLength(_even, rx * cx);   FillChar(_odd[0], rx * cx, 0); FillChar(_even[0], rx * cx, 0);   for var i := 0 to High(srcRows) do begin var r := srcRows[i];   var offset := (i + 1) * cx + 1; for var j := 1 to length(r) do _odd[offset + j - 1] := ord(r[j]); end;   while True do begin print(_odd); step(_even, _odd); Readln;   print(_even); step(_odd, _even); Readln; end; end;   begin Main;   {$IFNDEF UNIX} readln; {$ENDIF} end.
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
#Python
Python
#!/usr/bin/python   def isPrime(n): for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True   def isWeiferich(p): if not isPrime(p): return False q = 1 p2 = p ** 2 while p > 1: q = (2 * q) % p2 p -= 1 if q == 1: return True else: return False     if __name__ == '__main__': print("Wieferich primes less than 5000: ") for i in range(2, 5001): if isWeiferich(i): print(i)
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Quackery
Quackery
5000 eratosthenes   [ dup isprime iff [ dup 1 - bit 1 - swap dup * mod 0 = ] else [ drop false ] ] is wieferich ( n --> b )   5000 times [ i^ wieferich if [ i^ echo cr ] ]
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
#Racket
Racket
#lang typed/racket (require math/number-theory)   (: wieferich-prime? (-> Positive-Integer Boolean))   (define (wieferich-prime? p) (and (prime? p) (divides? (* p p) (sub1 (expt 2 (sub1 p))))))   (module+ main (define wieferich-primes<5000 (for/list : (Listof Integer) ((p (sequence-filter wieferich-prime? (in-range 1 5000)))) p)) wieferich-primes<5000)  
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
#Raku
Raku
put "Wieferich primes less than 5000: ", join ', ', ^5000 .grep: { .is-prime and not ( exp($_-1, 2) - 1 ) % .² };
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.
#Phix
Phix
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (load "@lib/misc.l" "@lib/gcc.l")   (gcc "x11" '("-lX11") 'simpleWin)   #include <X11/Xlib.h>   any simpleWin(any ex) { any x = cdr(ex); int dx, dy; Display *disp; int scrn; Window win; XEvent ev;   x = cdr(ex), dx = (int)evCnt(ex,x); x = cdr(x), dy = (int)evCnt(ex,x); x = evSym(cdr(x)); if (disp = XOpenDisplay(NULL)) { char msg[bufSize(x)];   bufString(x, msg); scrn = DefaultScreen(disp); win = XCreateSimpleWindow(disp, RootWindow(disp,scrn), 0, 0, dx, dy, 1, BlackPixel(disp,scrn), WhitePixel(disp,scrn) ); XSelectInput(disp, win, ExposureMask | KeyPressMask | ButtonPressMask); XMapWindow(disp, win); for (;;) { XNextEvent(disp, &ev); switch (ev.type) { case Expose: XDrawRectangle(disp, win, DefaultGC(disp, scrn), 10, 10, dx-20, dy-20); XDrawString(disp, win, DefaultGC(disp, scrn), 30, 40, msg, strlen(msg)); break; case KeyPress: case ButtonPress: XCloseDisplay(disp); return Nil; } } } return mkStr("Can't open Display"); } /**/   (simpleWin 300 200 "Hello World") (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.
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (load "@lib/misc.l" "@lib/gcc.l")   (gcc "x11" '("-lX11") 'simpleWin)   #include <X11/Xlib.h>   any simpleWin(any ex) { any x = cdr(ex); int dx, dy; Display *disp; int scrn; Window win; XEvent ev;   x = cdr(ex), dx = (int)evCnt(ex,x); x = cdr(x), dy = (int)evCnt(ex,x); x = evSym(cdr(x)); if (disp = XOpenDisplay(NULL)) { char msg[bufSize(x)];   bufString(x, msg); scrn = DefaultScreen(disp); win = XCreateSimpleWindow(disp, RootWindow(disp,scrn), 0, 0, dx, dy, 1, BlackPixel(disp,scrn), WhitePixel(disp,scrn) ); XSelectInput(disp, win, ExposureMask | KeyPressMask | ButtonPressMask); XMapWindow(disp, win); for (;;) { XNextEvent(disp, &ev); switch (ev.type) { case Expose: XDrawRectangle(disp, win, DefaultGC(disp, scrn), 10, 10, dx-20, dy-20); XDrawString(disp, win, DefaultGC(disp, scrn), 30, 40, msg, strlen(msg)); break; case KeyPress: case ButtonPress: XCloseDisplay(disp); return Nil; } } } return mkStr("Can't open Display"); } /**/   (simpleWin 300 200 "Hello World") (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.
#Python
Python
from Xlib import X, display   class Window: def __init__(self, display, msg): self.display = display self.msg = msg   self.screen = self.display.screen() self.window = self.screen.root.create_window( 10, 10, 100, 100, 1, self.screen.root_depth, background_pixel=self.screen.white_pixel, event_mask=X.ExposureMask | X.KeyPressMask, ) self.gc = self.window.create_gc( foreground = self.screen.black_pixel, background = self.screen.white_pixel, )   self.window.map()   def loop(self): while True: e = self.display.next_event()   if e.type == X.Expose: self.window.fill_rectangle(self.gc, 20, 20, 10, 10) self.window.draw_text(self.gc, 10, 50, self.msg) elif e.type == X.KeyPress: raise SystemExit     if __name__ == "__main__": Window(display.Display(), "Hello, World!").loop()
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.
#Fantom
Fantom
  using fwt   class Main { public static Void main () { Window().open } }  
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.
#Forth
Forth
include ffl/gsv.fs   \ Open the connection to the gtk-server and load the Gtk2 definitions s" gtk-server.cfg" s" ffl-fifo" gsv+open 0= [IF]   \ Convert the string event to a widget id : event>widget 0. 2swap >number 2drop d>s ;   0 value window   : window-creation gtk_init   \ Create the window GTK_WINDOW_TOPLEVEL gtk_window_new to window   window gtk_widget_show   \ Wait for an event BEGIN s" WAIT" gtk_server_callback event>widget window = UNTIL   0 gtk_exit ;   window-creation   gsv+close drop [THEN]
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
#zkl
zkl
fcn buildVectors(R,C){ //-->up to 8 vectors of wild card strings var [const] dirs=T(T(1,0), T(0,1), T(1,1), T(1,-1), T(-1,0),T(0,-1), T(-1,-1), T(-1,1)); vs,v:=List(),List(); foreach dr,dc in (dirs){ v.clear(); r,c:=R,C; while( (0<=r<10) and (0<=c<10) ){ v.append(grid[r][c]); r+=dr; c+=dc; } vs.append(T(v.concat(), // eg "???e??????" would match "cohen" or "mineral" dr,dc)); } vs.filter(fcn(v){ v[0].len()>2 }).shuffle() } fcn findFit(vs,words){ //-->(n, word) ie (nth vector,word), empty vs not seen do(1000){ foreach n,v in (vs.enumerate()){ do(10){ // lots of ties word:=words[(0).random(nwds)]; if(word.matches(v[0][0,word.len()])) return(word,n); // "??" !match "abc" }}} False } fcn pasteWord(r,c, dr,dc, word) // jam word into grid along vector { foreach char in (word){ grid[r][c]=char; r+=dr; c+=dc; } } fcn printGrid{ println("\n 0 1 2 3 4 5 6 7 8 9"); foreach n,line in (grid.enumerate()){ println(n," ",line.concat(" ")) } } fcn stuff(msg){ MSG:=msg.toUpper() : Utils.Helpers.cycle(_); foreach r,c in (10,10){ if(grid[r][c]=="?") grid[r][c]=MSG.next() } MSG._n==msg.len() // use all of, not more, not less, of msg? }
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Factor
Factor
USE: wrap.strings IN: scratchpad "Most languages in widespread use today are applicative languages : the central construct in the language is some form of function call, where a f unction is applied to a set of parameters, where each parameter is itself the re sult of a function call, the name of a variable, or a constant. In stack languag es, a function call is made by simply writing the name of the function; the para meters are implicit, and they have to already be on the stack when the call is m ade. The result of the function call (if any) is then left on the stack after th e function returns, for the next function to consume, and so on. Because functio ns are invoked simply by mentioning their name without any additional syntax, Fo rth and Factor refer to functions as words, because in the syntax they really ar e just words." [ 60 wrap-string print nl ] [ 45 wrap-string print ] bi
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
#Forth
Forth
\ wrap text \ usage: gforth wrap.f in.txt 72   0. argc @ 1- arg >number 2drop drop constant maxLine   : .wrapped ( buf len -- ) begin dup maxLine > while over maxLine begin 1- 2dup + c@ bl = until dup 1+ >r begin 1- 2dup + c@ bl <> until 1+ type cr r> /string repeat type cr ;   : strip-nl ( buf len -- ) bounds do i c@ 10 = if bl i c! then loop ;   argc @ 2 - arg slurp-file 2dup strip-nl .wrapped bye
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
#Wren
Wren
import "io" for File import "/sort" for Sort, Find import "/seq" for Lst   var letters = ["d", "e", "e", "g", "k", "l", "n", "o","w"]   var words = File.read("unixdict.txt").split("\n") // get rid of words under 3 letters or over 9 letters words = words.where { |w| w.count > 2 && w.count < 10 }.toList var found = [] for (word in words) { if (word.indexOf("k") >= 0) { var lets = letters.toList var ok = true for (c in word) { var ix = Find.first(lets, c) if (ix == - 1) { ok = false break } lets.removeAt(ix) } if (ok) found.add(word) } }   System.print("The following %(found.count) words are the solutions to the puzzle:") System.print(found.join("\n"))   // optional extra var mostFound = 0 var mostWords9 = [] var mostLetters = [] // iterate through all 9 letter words in the dictionary for (word9 in words.where { |w| w.count == 9 }) { letters = word9.toList Sort.insertion(letters) // get distinct letters var distinctLetters = Lst.distinct(letters) // place each distinct letter in the middle and see what we can do with the rest for (letter in distinctLetters) { found = 0 for (word in words) { if (word.indexOf(letter) >= 0) { var lets = letters.toList var ok = true for (c in word) { var ix = Find.first(lets, c) if (ix == - 1) { ok = false break } lets.removeAt(ix) } if (ok) found = found + 1 } } if (found > mostFound) { mostFound = found mostWords9 = [word9] mostLetters = [letter] } else if (found == mostFound) { mostWords9.add(word9) mostLetters.add(letter) } } } System.print("\nMost words found = %(mostFound)") System.print("Nine letter words producing this total:") for (i in 0...mostWords9.count) { System.print("%(mostWords9[i]) with central letter '%(mostLetters[i])'") }
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.
#OCaml
OCaml
# #directory "+xml-light" (* or maybe "+site-lib/xml-light" *) ;;   # #load "xml-light.cma" ;;   # let data = [ ("April", "Bubbly: I'm > Tam and <= Emily"); ("Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\""); ("Emily", "Short & shrift"); ] in let tags = List.map (fun (name, comment) -> Xml.Element ("Character", [("name", name)], [(Xml.PCData comment)]) ) data in print_endline ( Xml.to_string_fmt (Xml.Element ("CharacterRemarks", [], tags))) ;; <CharacterRemarks> <Character name="April">Bubbly: I&apos;m &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: &quot;When chapman billies leave the street ...&quot;</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> - : unit = ()
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
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Const Enumerator=-4& xml$={<Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> } Declare Dom "Msxml2.DOMDocument" Method Dom, "LoadXML", xml$ Method Dom, "getElementsByTagName", "Student" as Students   With Students, Enumerator as Student While Student { Method Student, "getAttribute", "Name" as Student.Name$ Print Student.Name$ } Declare Student Nothing Declare Students Nothing Declare DOM Nothing } CheckIt  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Column[Cases[Import["test.xml","XML"],Rule["Name", n_ ] -> n,Infinity]]
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)
#VHDL
VHDL
  entity Array_Test is end entity Array_Test;   architecture Example of Array_test is   -- Array type have to be defined first type Integer_Array is array (Integer range <>) of Integer;   -- Array index range can be ascending... signal A : Integer_Array (1 to 20);   -- or descending signal B : Integer_Array (20 downto 1);   -- VHDL array index ranges may begin at any value, not just 0 or 1 signal C : Integer_Array (-37 to 20);   -- VHDL arrays may be indexed by enumerated types, which are -- discrete non-numeric types type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun); type Activities is (Work, Fish); type Daily_Activities is array (Days) of Activities; signal This_Week : Daily_Activities := (Mon to Fri => Work, Others => Fish);   type Finger is range 1 to 4; -- exclude thumb type Fingers_Extended is array (Finger) of Boolean; signal Extended : Fingers_Extended;   -- Array types may be unconstrained. -- Objects of the type must be constrained type Arr is array (Integer range <>) of Integer; signal Uninitialized : Arr (1 to 10); signal Initialized_1 : Arr (1 to 20) := (others => 1); constant Initialized_2 : Arr := (1 to 30 => 2); constant Const : Arr := (1 to 10 => 1, 11 to 20 => 2, 21 | 22 => 3); signal Centered : Arr (-50 to 50) := (0 => 1, others => 0);   signal Result : Integer;   begin   A <= (others => 0); -- Assign whole array B <= (1 => 1, 2 => 1, 3 => 2, others => 0); -- Assign whole array, different values A (1) <= -1; -- Assign individual element A (2 to 4) <= B (3 downto 1); -- Assign a slice A (3 to 5) <= (2, 4, -1); -- Assign an aggregate A (3 to 5) <= A (4 to 6); -- It is OK to overlap slices when assigned   -- VHDL arrays does not have 'first' and 'last' elements, -- but have 'Left' and 'Right' instead Extended (Extended'Left) <= False; -- Set leftmost element of array Extended (Extended'Right) <= False; -- Set rightmost element of array   Result <= A (A'Low) + B (B'High);   end architecture Example;  
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.
#Yabasic
Yabasic
x$ = "1 2 3 1e11" pr1 = 3 : pr2 = 5   dim x$(1) n = token(x$, x$())   f = open("filename.txt", "w")   for i = 1 to n print #f str$(val(x$(i)), "%1." + str$(pr1) + "g") + "\t" + str$(sqrt(val(x$(i))), "%1." + str$(pr2) + "g") next i   close #f
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.
#zkl
zkl
fcn writeFloatArraysToFile(filename, xs,xprecision, ys,yprecision){ f  :=File(filename,"w"); fmt:="%%.%dg\t%%.%dg".fmt(xprecision,yprecision).fmt; // "%.3g\t%.5g".fmt foreach x,y in (xs.zip(ys)){ f.writeln(fmt(x,y)); } f.close(); }   xs,ys := T(1.0, 2.0, 3.0, 1e11), xs.apply("sqrt"); xprecision,yprecision := 3,5; writeFloatArraysToFile("floatArray.txt", xs,xprecision, ys,yprecision);
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.
#Nial
Nial
n:=100;reduce xor (count n eachright mod count n eachall<1) looloooolooooooloooooooolooooooooooloooooooooooolooooooooooooooloooooooooooooooo   looooooooooooooooool
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
#Go
Go
package main   import "fmt"   func divisors(n int) []int { divs := []int{1} divs2 := []int{} for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i divs = append(divs, i) if i != j { divs2 = append(divs2, j) } } } for i := len(divs) - 1; i >= 0; i-- { divs2 = append(divs2, divs[i]) } return divs2 }   func abundant(n int, divs []int) bool { sum := 0 for _, div := range divs { sum += div } return sum > n }   func semiperfect(n int, divs []int) bool { le := len(divs) if le > 0 { h := divs[0] t := divs[1:] if n < h { return semiperfect(n, t) } else { return n == h || semiperfect(n-h, t) || semiperfect(n, t) } } else { return false } }   func sieve(limit int) []bool { // false denotes abundant and not semi-perfect. // Only interested in even numbers >= 2 w := make([]bool, limit) 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 } } } return w }   func main() { w := sieve(17000) count := 0 const max = 25 fmt.Println("The first 25 weird numbers are:") for n := 2; count < max; n += 2 { if !w[n] { fmt.Printf("%d ", n) count++ } } fmt.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
#Modula-2
Modula-2
MODULE Art; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   BEGIN (* 3D, but does not fit in the terminal window *) (* WriteString("_____ ______ ________ ________ ___ ___ ___ ________ _______"); WriteLn; WriteString("|\ _ \ _ \|\ __ \|\ ___ \|\ \|\ \|\ \ |\ __ \ / ___ \"); WriteLn; WriteString("\ \ \\\__\ \ \ \ \|\ \ \ \_|\ \ \ \\\ \ \ \ \ \ \|\ \ ____________ /__/|_/ /|"); WriteLn; WriteString(" \ \ \\|__| \ \ \ \\\ \ \ \ \\ \ \ \\\ \ \ \ \ \ __ \|\____________\__|// / /"); WriteLn; WriteString(" \ \ \ \ \ \ \ \\\ \ \ \_\\ \ \ \\\ \ \ \____\ \ \ \ \|____________| / /_/__"); WriteLn; WriteString(" \ \__\ \ \__\ \_______\ \_______\ \_______\ \_______\ \__\ \__\ |\________\"); WriteLn; WriteString(" \|__| \|__|\|_______|\|_______|\|_______|\|_______|\|__|\|__| \|_______|"); WriteLn; *)   (* Not 3D, but fits in the terminal window *) WriteString(" __ __ _ _ ___"); WriteLn; WriteString(" | \/ | | | | | |__ \"); WriteLn; WriteString(" | \ / | ___ __| |_ _| | __ _ ______ ) |"); WriteLn; WriteString(" | |\/| |/ _ \ / _` | | | | |/ _` |______/ /"); WriteLn; WriteString(" | | | | (_) | (_| | |_| | | (_| | / /_"); WriteLn; WriteString(" |_| |_|\___/ \__,_|\__,_|_|\__,_| |____|"); WriteLn;   ReadChar END Art.
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++.
#C.23
C#
class Program { static void Main(string[] args) { WebClient wc = new WebClient(); Stream myStream = wc.OpenRead("http://tycho.usno.navy.mil/cgi-bin/timer.pl"); string html = ""; using (StreamReader sr = new StreamReader(myStream)) { while (sr.Peek() >= 0) { html = sr.ReadLine(); if (html.Contains("UTC")) { break; } }   } Console.WriteLine(html.Remove(0, 4));   Console.ReadLine(); } }  
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.
#Ring
Ring
    Load "guilib.ring"   /* +-------------------------------------------------------------------------- + Program Name : ScreenDrawOnReSize.ring + Date  : 2016.06.16 + Author  : Bert Mariani + Purpose  : Re-Draw Chart after ReSize or move +-------------------------------------------------------------------------- */     ###------------------------------- ### DRAW CHART size 1000 x 1000 ###   ###------------------------------   ### Window Size WinLeft = 80 ### 80 Window position on screen WinTop = 80 ### 80 Window position on screen WinWidth = 1000 ### 1000 Window Size - Horizontal-X WinWidth WinHeight = 750 ### 750 Window Size - Vertical-Y WinHeight WinRight = WinLeft + WinWidth ### 1080 WinBottom = WinTop + WinHeight ### 830   ### Label Box Size BoxLeft = 40 ### Start corner Label1 Box Start Position inside WIN1 BoxTop = 40 ### Start corner BoxWidth = WinWidth -80 ### End corner Label1 Box Size BoxHeight = WinHeight -80 ### End corner   ###----------------------------     New qapp { win1 = new qwidget() {   ### Position and Size of WINDOW on the Screen setwindowtitle("DrawChart using QPainter") setgeometry( WinLeft, WinTop, WinWidth, WinHeight)   win1{ setwindowtitle("Initial Window Position: " +" L " + WinLeft +" T " + WinTop +" Width" + width() +" Height " + height() ) }   ### ReSizeEvent ... Call WhereAreWe function myfilter = new qallevents(win1) myfilter.setResizeEvent("WhereAreWe()") installeventfilter(myfilter)   ### Draw within this BOX label1 = new qlabel(win1) { setgeometry(BoxLeft, BoxTop, BoxWidth, BoxHeight) settext("We are Here") }     ### Button Position and Size ... Call DRAW function new qpushbutton(win1) { setgeometry( 30, 30, 80, 20) settext("Draw") setclickevent("Draw()") }   ###---------------   show() }   exec() }     ###----------------- ### FUNCTION Draw ###-----------------   Func WhereAreWe Rec = win1.framegeometry()   WinWidth = win1.width() ### 1000 Current Values WinHeight = win1.height() ### 750   WinLeft = Rec.left() +8 ### <<< QT FIX because of Win Title WinTop = Rec.top() +30 ### <<< QT FIX because of Win Title WinRight = Rec.right() WinBottom = Rec.bottom()   BoxWidth = WinWidth -80 ### 950 BoxHeight = WinHeight -80 ### 700   win1{ setwindowtitle("Window ReSize: Win " + WinWidth + "x" + WinHeight + " --- Box " + BoxWidth + "x" + BoxHeight + " --- LT " + WinLeft + "-" + WinTop + " --- RB " + WinRight + "-" + WinBottom ) }   See "We Are Here - setResizeEvent - " See " Win " + WinWidth + "x" + WinHeight + " --- Box " + BoxWidth + "x" + BoxHeight See " --- LT " + Winleft + "-" + WinTop + " --- RB " + WinRight + "-" + WinBottom +nl   win1.setgeometry( WinLeft, WinTop, WinWidth, WinHeight ) label1.setgeometry( BoxLeft, BoxTop, BoxWidth, BoxHeight )     return   Func Draw   win1{ setwindowtitle("Draw Position: Win " + WinWidth + "x" + WinHeight + " --- Box " + BoxWidth + "x" + BoxHeight + " --- LT " + WinLeft + "-" + WinTop + " --- RB " + WinRight + "-" + WinBottom ) }   See "Draw Position: " + WinWidth + "x" + WinHeight + " --- Box " + BoxWidth + "x" + BoxHeight + " --- LT " + WinLeft + "-" + WinTop + " --- RB " + WinRight + "-" + WinBottom + nl     # ##----------------------------- ### PEN Colors   p1 = new qpicture()   colorBlue = new qcolor() { setrgb(0, 0,255,255) } penBlue = new qpen() { setcolor(colorBlue) setwidth(1) }     ###----------------------- ### PAINT the Chart   new qpainter() { begin(p1) setpen(penBlue)   ###--------------------- ### Draw Line Chart   drawline( 1 , 1 , BoxWidth , 1 ) ### WinTop line horizonal drawline( 1 , 1 , 1 , BoxHeight ) ### WinLeft Line vetical   drawline( 1 , BoxHeight , BoxWidth , BoxHeight ) ### Bottom Line horizontal drawline( BoxWidth , 1 , BoxWidth , BoxHeight ) ### WinRight Line vertical   drawline( BoxWidth / 2 , 1 , BoxWidth / 2 , BoxHeight ) ### Central vertical drawline( 1 , BoxHeight / 2 , BoxWidth , BoxHeight / 2 ) ### Central horizontal     ###--------------------------------------------------     endpaint() }     label1 { setpicture(p1) show() }   return ###--------------------------------------------    
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.
#Tcl
Tcl
package require Tk   # How to open a window proc openWin {} { global win if {[info exists win] && [winfo exists $win]} { # Already existing; just reset wm deiconify $win wm state $win normal return } catch {destroy $win} ;# Squelch the old one set win [toplevel .t] pack [label $win.label -text "This is the window being manipulated"] \ -fill both -expand 1 } # How to close a window proc closeWin {} { global win if {[info exists win] && [winfo exists $win]} { destroy $win } } # How to minimize a window proc minimizeWin {} { global win if {[info exists win] && [winfo exists $win]} { wm state $win iconic } } # How to maximize a window proc maximizeWin {} { global win if {[info exists win] && [winfo exists $win]} { wm state $win zoomed catch {wm attribute $win -zoomed 1} ;# Hack for X11 } } # How to move a window proc moveWin {} { global win if {[info exists win] && [winfo exists $win]} { scan [wm geometry $win] "%dx%d+%d+%d" width height x y wm geometry $win +[incr x 10]+[incr y 10] } } # How to resize a window proc resizeWin {} { global win if {[info exists win] && [winfo exists $win]} { scan [wm geometry $win] "%dx%d+%d+%d" width height x y wm geometry $win [incr width 10]x[incr height 10] } }   grid [label .l -text "Window handle:"] [label .l2 -textvariable win] grid [button .b1 -text "Open/Reset" -command openWin] - grid [button .b2 -text "Close" -command closeWin] - grid [button .b3 -text "Minimize" -command minimizeWin] - grid [button .b4 -text "Maximize" -command maximizeWin] - grid [button .b5 -text "Move" -command moveWin] - grid [button .b6 -text "Resize" -command resizeWin] -
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
#Bracmat
Bracmat
( 10-most-frequent-words = MergeSort { Local variable declarations. } types sorted-words frequency type most-frequent-words . ( MergeSort { Definition of function MergeSort. } = A N Z pivot .  !arg:? [?N { [?N is a subpattern that counts the number of preceding elements } & (  !N:>1 { if N at least 2 ... } & div$(!N.2):?pivot { divide N by 2 ... } & !('($arg:?A [($pivot) ?Z)) { split list in two halves A and Z ... } & MergeSort$!A+MergeSort$!Z { sort each of A and Z and return sum } | !arg { else just return a single element} ) ) & MergeSort { Sort } $ ( vap { Split second argument at each occurrence of third character and apply first argument to each chunk. } $ ( (=.low$!arg) { Return input, lowercased. } . str $ ( vap { Vaporize second argument in UTF-8 or Latin-1 characters and apply first argument to each of them. } $ ( ( = . upp$!arg:low$!arg&\n { Return newline instead of non-alphabetic character. } | !arg { Return (Euro-centric) alphabetic character.} ) . get$(!arg,NEW STR) { Read input text as a single string. } ) ) . \n { Split at newlines } ) )  : ?sorted-words { Assign sum of (frequency*lowercasedword) terms to sorted-words. } & :?types { Initialize types as an empty list. } & whl { Loop until right hand side fails. } ' ( !sorted-words:#?frequency*%@?type+?sorted-words { Extract first frequency*type term from sum. } & (!frequency.!type) !types:?types { Prepend (frequency.type) pair to types list} ) & MergeSort$!types { Sort the list of (frequency.type) pairs. }  : (?+[-11+?most-frequent-words|?most-frequent-words) { Pick the last 10 terms from the sum returned by MergeSort. } & !most-frequent-words { Return the last 10 terms. } ) & out$(10-most-frequent-words$"135-0.txt") { Call 10-most-frequent-words with name of inout file and print result to screen. }
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
#C
C
#include <stdbool.h> #include <stdio.h> #include <glib.h>   typedef struct word_count_tag { const char* word; size_t count; } word_count;   int compare_word_count(const void* p1, const void* p2) { const word_count* w1 = p1; const word_count* w2 = p2; if (w1->count > w2->count) return -1; if (w1->count < w2->count) return 1; return 0; }   bool get_top_words(const char* filename, size_t count) { GError* error = NULL; GMappedFile* mapped_file = g_mapped_file_new(filename, FALSE, &error); if (mapped_file == NULL) { fprintf(stderr, "%s\n", error->message); g_error_free(error); return false; } const char* text = g_mapped_file_get_contents(mapped_file); if (text == NULL) { fprintf(stderr, "File %s is empty\n", filename); g_mapped_file_unref(mapped_file); return false; } gsize file_size = g_mapped_file_get_length(mapped_file); // Store word counts in a hash table GHashTable* ht = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free); GRegex* regex = g_regex_new("\\w+", 0, 0, NULL); GMatchInfo* match_info; g_regex_match_full(regex, text, file_size, 0, 0, &match_info, NULL); while (g_match_info_matches(match_info)) { char* word = g_match_info_fetch(match_info, 0); char* lower = g_utf8_strdown(word, -1); g_free(word); size_t* count = g_hash_table_lookup(ht, lower); if (count != NULL) { ++*count; g_free(lower); } else { count = g_new(size_t, 1); *count = 1; g_hash_table_insert(ht, lower, count); } g_match_info_next(match_info, NULL); } g_match_info_free(match_info); g_regex_unref(regex); g_mapped_file_unref(mapped_file);   // Sort words in decreasing order of frequency size_t size = g_hash_table_size(ht); word_count* words = g_new(word_count, size); GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, ht); for (size_t i = 0; g_hash_table_iter_next(&iter, &key, &value); ++i) { words[i].word = key; words[i].count = *(size_t*)value; } qsort(words, size, sizeof(word_count), compare_word_count);   // Print the most common words if (count > size) count = size; printf("Top %lu words\n", count); printf("Rank\tCount\tWord\n"); for (size_t i = 0; i < count; ++i) printf("%lu\t%lu\t%s\n", i + 1, words[i].count, words[i].word); g_free(words); g_hash_table_destroy(ht); return true; }   int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "usage: %s file\n", argv[0]); return EXIT_FAILURE; } if (!get_top_words(argv[1], 10)) return EXIT_FAILURE; return EXIT_SUCCESS; }
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.
#Elena
Elena
import system'routines; import extensions; import cellular;   const string sample = " tH...... . ...... ...Ht... . .... . ..... .... ......tH . . ...... ...Ht...";   const string conductorLabel = "."; const string headLabel = "H"; const string tailLabel = "t"; const string emptyLabel = " ";   const int empty = 0; const int conductor = 1; const int electronHead = 2; const int electronTail = 3;   wireWorldRuleSet = new RuleSet { proceed(Space s, int x, int y, ref int retVal) { int cell := s.at(x, y);   cell => conductor { int number := s.LiveCell(x, y, electronHead); if (number == 1 || number == 2) { retVal := electronHead } else { retVal := conductor } } electronHead { retVal := electronTail } electronTail { retVal := conductor }  :{ retVal := cell } } };   sealed class Model { Space theSpace;   constructor load(string stateString, int maxX, int maxY) { var strings := stateString.splitBy(newLine).selectBy:(s => s.toArray()).toArray();   theSpace := IntMatrixSpace.allocate(maxX, maxY, RuleSet { proceed(Space s, int x, int y, ref int retVal) { if (x < strings.Length) { var l := strings[x]; if (y < l.Length) { (l[y]) => conductorLabel { retVal := conductor } headLabel { retVal := electronHead } tailLabel { retVal := electronTail } emptyLabel { retVal := empty } } else { retVal := empty } } else { retVal := empty }   } }) }   run() { theSpace.update(wireWorldRuleSet) }   print() { int columns := theSpace.Columns; int rows := theSpace.Rows;   int i := 0; int j := 0; while (i < rows) { j := 0;   while (j < columns) { var label := emptyLabel; int cell := theSpace.at(i, j);   cell => conductor { label := conductorLabel } electronHead { label := headLabel } electronTail { label := tailLabel };   console.write(label);   j := j + 1 };   i := i + 1; console.writeLine() } } }   public program() { Model model := Model.load(sample,10,30); for(int i := 0, i < 10, i += 1) { console.printLineFormatted("Iteration {0}",i); model.print().run() } }
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.
#Elixir
Elixir
defmodule Wireworld do @empty " " @head "H" @tail "t" @conductor "." @neighbours (for x<- -1..1, y <- -1..1, do: {x,y}) -- [{0,0}]   def set_up(string) do lines = String.split(string, "\n", trim: true) grid = Enum.with_index(lines) |> Enum.flat_map(fn {line,i} -> String.codepoints(line) |> Enum.with_index |> Enum.map(fn {char,j} -> {{i, j}, char} end) end) |> Enum.into(Map.new) width = Enum.map(lines, fn line -> String.length(line) end) |> Enum.max height = length(lines) {grid, width, height} end   # to string defp to_s(grid, width, height) do Enum.map_join(0..height-1, fn i -> Enum.map_join(0..width-1, fn j -> Map.get(grid, {i,j}, @empty) end) <> "\n" end) end   # transition all cells simultaneously defp transition(grid) do Enum.into(grid, Map.new, fn {{x, y}, state} -> {{x, y}, transition_cell(grid, state, x, y)} end) end   # how to transition a single cell defp transition_cell(grid, current, x, y) do case current do @empty -> @empty @head -> @tail @tail -> @conductor _ -> if neighbours_with_state(grid, x, y) in 1..2, do: @head, else: @conductor end end   # given a position in the grid, find the neighbour cells with a particular state def neighbours_with_state(grid, x, y) do Enum.count(@neighbours, fn {dx,dy} -> Map.get(grid, {x+dx, y+dy}) == @head end) end   # run a simulation up to a limit of transitions, or until a recurring # pattern is found # This will print text to the console def run(string, iterations\\25) do {grid, width, height} = set_up(string) Enum.reduce(0..iterations, {grid, %{}}, fn count,{grd, seen} -> IO.puts "Generation : #{count}" IO.puts to_s(grd, width, height)   if seen[grd] do IO.puts "I've seen this grid before... after #{count} iterations" exit(:normal) else {transition(grd), Map.put(seen, grd, count)} end end) IO.puts "ran through #{iterations} iterations" end end   # this is the "2 Clock generators and an XOR gate" example from the wikipedia page text = """ ......tH . ...... ...Ht... . .... . ..... .... tH...... . . ...... ...Ht... """   Wireworld.run(text)
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
#REXX
REXX
/*REXX program finds and displays Wieferich primes which are under a specified limit N*/ parse arg n . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n= 5000 /*Not specified? Then use the default.*/ numeric digits 3000 /*bump # of dec. digs for calculation. */ numeric digits max(9, length(2**n) ) /*calculate # of decimal digits needed.*/ call genP /*build array of semaphores for primes.*/ title= ' Wieferich primes that are < ' commas(n) /*title for the output.*/ w= length(title) + 2 /*width of field for the primes listed.*/ say ' index │'center(title, w) /*display the title for the output. */ say '───────┼'center("" , w, '─') /* " a sep " " " */ found= 0 /*initialize number of Wieferich primes*/ do j=1 to #; p= @.j /*search for Wieferich primes in range.*/ if (2**(p-1)-1)//p**2\==0 then iterate /*P**2 not evenly divide 2**(P-1) - 1?*/ /* ◄■■■■■■■ the filter.*/ found= found + 1 /*bump the counter of Wieferich primes.*/ say center(found, 7)'│' center(commas(p), w) /*display the Wieferich prime.*/ end /*j*/   say '───────┴'center("" , w, '─'); say /*display a foot sep for the output. */ say 'Found ' commas(found) title /* " " summary " " " */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? /*──────────────────────────────────────────────────────────────────────────────────────*/ genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11 /*define some low primes (index-1). */  !.=0;  !.2=1; !.3=1; !.5=1; !.7=1; !.11=1 /* " " " " (semaphores).*/ #= 5; sq.#= @.# ** 2 /*number of primes so far; prime². */ do j=@.#+2 by 2 to n-1; parse var j '' -1 _ /*get right decimal digit of J.*/ if _==5 then iterate /*J ÷ by 5? Yes, skip.*/ if j//3==0 then iterate; if j//7==0 then iterate /*" " " 3? J ÷ by 7? */ do k=5 while sq.k<=j /* [↓] divide by the known odd primes.*/ if j//@.k==0 then iterate j /*Is J ÷ a P? Then not prime. ___ */ end /*k*/ /* [↑] only process numbers ≤ √ J */ #= #+1; @.#= j; sq.#= j*j;  !.j= 1 /*bump # Ps; assign next P; P sqare; P.*/ end /*j*/; return
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.
#Racket
Racket
#lang racket/gui   (define frame (new frame% [label "Example"] [width 300] [height 300])) (new canvas% [parent frame] [paint-callback (lambda (canvas dc) (send dc set-scale 3 3) (send dc set-text-foreground "blue") (send dc draw-text "Don't Panic!" 0 0))]) (send frame show #t)
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.
#Raku
Raku
use NativeCall;   class Display is repr('CStruct') { has int32 $!screen; has int32 $!window; } class GC is repr('CStruct') { has int32 $!context; } class XEvent is repr('CStruct') { has int32 $.type; method init { $!type = 0 } }   sub XOpenDisplay(Str $name = ':0') returns Display is native('X11') { * } sub XDefaultScreen(Display $) returns int32 is native('X11') { * } sub XRootWindow(Display $, int32 $screen_number) returns int32 is native('X11') { * } sub XBlackPixel(Display $, int32 $screen_number) returns int32 is native('X11') { * } sub XWhitePixel(Display $, int32 $screen_number) returns int32 is native('X11') { * } sub XCreateSimpleWindow( Display $, int32 $parent_window, int32 $x, int32 $y, int32 $width, int32 $height, int32 $border_width, int32 $border, int32 $background ) returns int32 is native('X11') { * } sub XMapWindow(Display $, int32 $window) is native('X11') { * } sub XSelectInput(Display $, int32 $window, int32 $mask) is native('X11') { * } sub XFillRectangle( Display $, int32 $window, GC $, int32 $x, int32 $y, int32 $width, int32 $height ) is native('X11') { * } sub XDrawString( Display $, int32 $window, GC $, int32 $x, int32 $y, Str $, int32 $str_length ) is native('X11') { * } sub XDefaultGC(Display $, int32 $screen) returns GC is native('X11') { * } sub XNextEvent(Display $, XEvent $e) is native('X11') { * } sub XCloseDisplay(Display $) is native('X11') { * }   my Display $display = XOpenDisplay() or die "Can not open display";   my int $screen = XDefaultScreen($display); my int $window = XCreateSimpleWindow( $display, XRootWindow($display, $screen), 10, 10, 100, 100, 1, XBlackPixel($display, $screen), XWhitePixel($display, $screen) ); XSelectInput($display, $window, 1 +< 15 +| 1); XMapWindow($display, $window);   my Str $msg = 'Hello, World!'; my XEvent $e .= new; $e.init; loop { XNextEvent($display, $e); if $e.type == 12 { XFillRectangle($display, $window, XDefaultGC($display, $screen), 20, 20, 10, 10); XDrawString($display, $window, XDefaultGC($display, $screen), 10, 50, $msg, my int $ = $msg.chars); } elsif $e.type == 2 { last; } } XCloseDisplay($display);
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.
#FreeBASIC
FreeBASIC
  #Include "windows.bi"   Dim As HWND Window_Main Dim As MSG msg   'Create the window: Window_Main = CreateWindow("#32770", "I am a window - close me!", WS_OVERLAPPEDWINDOW Or WS_VISIBLE, 100, 100, 350, 200, 0, 0, 0, 0)   'Windows message loop: While GetMessage(@msg, Window_Main, 0, 0) TranslateMessage(@msg) DispatchMessage(@msg) If msg.hwnd = Window_Main And msg.message = WM_COMMAND Then End Wend   End  
http://rosettacode.org/wiki/Window_creation
Window creation
Display a GUI window. The window need not have any contents, but should respond to requests to be closed.
#Frink
Frink
  g=(new graphics).show[]  
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
#Fortran
Fortran
CHARACTER*12345 TEXT ... DO I = 0,120 WRITE (6,*) TEXT(I*80 + 1:(I + 1)*80) END DO
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
#XPL0
XPL0
string 0; \use zero-terminated strings int I, Set, HasK, HasOther, HasDup, ECnt, Ch; char Word(25); def LF=$0A, CR=$0D, EOF=$1A; [FSet(FOpen("unixdict.txt", 0), ^I); OpenI(3); repeat I:= 0; HasK:= false; HasOther:= false; ECnt:= 0; Set:= 0; HasDup:= false; loop [repeat Ch:= ChIn(3) until Ch # CR; \remove possible CR if Ch=LF or Ch=EOF then quit; Word(I):= Ch; I:= I+1; if Ch = ^k then HasK:= true; case Ch of ^k,^n,^d,^e,^o,^g,^l,^w: [] \assume all lowercase other HasOther:= true; if Ch = ^e then ECnt:= ECnt+1 else [if Set & 1<<(Ch-^a) then HasDup:= true; Set:= Set ! 1<<(Ch-^a); ]; ]; Word(I):= 0; \terminate string if I>=3 & HasK & ~HasOther & ~HasDup & ECnt<=2 then [Text(0, Word); CrLf(0); ]; until Ch = EOF; ]
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.
#Oz
Oz
declare proc {Main} Names = ["April" "Tam O'Shanter" "Emily"]   Remarks = ["Bubbly: I'm > Tam and <= Emily" "Burns: \"When chapman billies leave the street ...\"" "Short & shrift"]   Characters = {List.zip Names Remarks fun {$ N R} 'Character'(name:N R) end}   DOM = {List.toTuple 'CharacterRemarks' Characters} in {System.showInfo {Serialize DOM}} end   fun {Serialize DOM} "<?xml version=\"1.0\" ?>\n"# {SerializeElement DOM 0} end   fun {SerializeElement El Indent} Name = {Label El} Attributes ChildElements Contents {DestructureElement El ?Attributes ?ChildElements ?Contents} EscContents = {Map Contents Escape} Spaces = {List.make Indent} for S in Spaces do S = & end in Spaces#"<"#Name# {VSConcatMap Attributes SerializeAttribute}#">"# {VSConcat EscContents}#{When ChildElements\=nil "\n"}# {VSConcatMap ChildElements fun {$ E} {SerializeElement E Indent+4} end}# {When ChildElements\=nil Spaces}#"</"#Name#">\n" end   proc {DestructureElement El ?Attrs ?ChildElements ?Contents} SubelementRec AttributeRec {Record.partitionInd El fun {$ I _} {Int.is I} end  ?SubelementRec ?AttributeRec} Subelements = {Record.toList SubelementRec} in {List.partition Subelements VirtualString.is ?Contents ?ChildElements} Attrs = {Record.toListInd AttributeRec} end   fun {SerializeAttribute Name#Value} " "#Name#"=\""#{EscapeAttribute Value}#"\"" end   fun {Escape VS} {Flatten {Map {VirtualString.toString VS} EscapeChar}} end   fun {EscapeAttribute VS} {Flatten {Map {VirtualString.toString VS} EscapeAttributeChar}} end   fun {EscapeChar X} case X of 60 then "&lt;" [] 62 then "&gt;" [] 38 then "&amp;" else X end end   fun {EscapeAttributeChar X} case X of 34 then "&quot;" else {EscapeChar X} end end   %% concatenates a list to a virtual string fun {VSConcat Xs} {List.toTuple '#' Xs} end   fun {VSConcatMap Xs F} {VSConcat {Map Xs F}} end   fun {When Cond X} if Cond then X else nil end end in {Main}
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
#MATLAB
MATLAB
RootXML = com.mathworks.xml.XMLUtils.createDocument('Students'); docRootNode = RootXML.getDocumentElement; thisElement = RootXML.createElement('Student'); thisElement.setAttribute('Name','April') thisElement.setAttribute('Gender','F') thisElement.setAttribute('DateOfBirth','1989-01-02') docRootNode.appendChild(thisElement); thisElement = RootXML.createElement('Student'); thisElement.setAttribute('Name','Bob') thisElement.setAttribute('Gender','M') thisElement.setAttribute('DateOfBirth','1990-03-04') docRootNode.appendChild(thisElement); thisElement = RootXML.createElement('Student'); thisElement.setAttribute('Name','Chad') thisElement.setAttribute('Gender','M') thisElement.setAttribute('DateOfBirth','1991-05-06') docRootNode.appendChild(thisElement); thisElement = RootXML.createElement('Student'); thisElement.setAttribute('Name','Dave') thisElement.setAttribute('Gender','M') thisElement.setAttribute('DateOfBirth','1992-07-08') node = RootXML.createElement('Pet'); node.setAttribute('Type','dog') node.setAttribute('name','Rover') thisElement.appendChild(node); docRootNode.appendChild(thisElement); thisElement = RootXML.createElement('Student'); thisElement.setAttribute('Name','Émily') thisElement.setAttribute('Gender','F') thisElement.setAttribute('DateOfBirth','1993-09-10') docRootNode.appendChild(thisElement); clearvars -except RootXML   for I=0:1:RootXML.getElementsByTagName('Student').item(0).getAttributes.getLength-1 if strcmp(RootXML.getElementsByTagName('Student').item(0).getAttributes.item(I).getName,'Name') tag=I; break end end   for I=0:1:RootXML.getElementsByTagName('Student').getLength-1 disp(RootXML.getElementsByTagName('Student').item(I).getAttributes.item(tag).getValue) end
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)
#Vim_Script
Vim Script
" Creating a dynamic array with some initial values let array = [3, 4]   " Retrieving an element let four = array[1]   " Modifying an element let array[0] = 2   " Appending a new element call add(array, 5)   " Prepending a new element call insert(array, 1)   " Inserting a new element before another element call insert(array, 3, 2)   echo array
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.
#ZX_Spectrum_Basic
ZX Spectrum Basic
SAVE "myarray" DATA g()
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.
#Nim
Nim
from strutils import `%`   const numDoors = 100 var doors: array[1..numDoors, bool]   for pass in 1..numDoors: for door in countup(pass, numDoors, pass): doors[door] = not doors[door]   for door in 1..numDoors: echo "Door $1 is $2." % [$door, if doors[door]: "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
#Haskell
Haskell
weirds :: [Int] weirds = filter abundantNotSemiperfect [1 ..]   abundantNotSemiperfect :: Int -> Bool abundantNotSemiperfect n = let ds = descProperDivisors n d = sum ds - n in 0 < d && not (hasSum d ds)   hasSum :: Int -> [Int] -> Bool hasSum _ [] = False hasSum n (x:xs) | n < x = hasSum n xs | otherwise = (n == x) || hasSum (n - x) xs || hasSum n xs   descProperDivisors :: Integral a => a -> [a] descProperDivisors n = let root = (floor . sqrt) (fromIntegral n :: Double) lows = filter ((0 ==) . rem n) [root,root - 1 .. 1] factors | n == root ^ 2 = tail lows | otherwise = lows in tail $ reverse (quot n <$> lows) ++ factors   main :: IO () main = (putStrLn . unlines) $ zipWith (\i x -> show i ++ (" -> " ++ show x)) [1 ..] (take 25 weirds)
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
#Nanoquery
Nanoquery
println " ________ ________ ________ ________ ________ ___ ___ _______ ________ ___ ___ " println "|\\ ___ \\|\\ __ \\|\\ ___ \\|\\ __ \\|\\ __ \\|\\ \\|\\ \\|\\ ___ \\ |\\ __ \\ |\\ \\ / /| " println "\\ \\ \\\\ \\ \\ \\ \\|\\ \\ \\ \\\\ \\ \\ \\ \\|\\ \\ \\ \\|\\ \\ \\ \\\\\\ \\ \\ __/|\\ \\ \\|\\ \\ \\ \\ \\/ / / " println " \\ \\ \\\\ \\ \\ \\ __ \\ \\ \\\\ \\ \\ \\ \\\\\\ \\ \\ \\\\\\ \\ \\ \\\\\\ \\ \\ \\_|/_\\ \\ _ _\\ \\ \\ / / " println " \\ \\ \\\\ \\ \\ \\ \\ \\ \\ \\ \\\\ \\ \\ \\ \\\\\\ \\ \\ \\\\\\ \\ \\ \\\\\\ \\ \\ \\_|\\ \\ \\ \\\\ \\| \\/ / / " println " \\ \\__\\\\ \\__\\ \\__\\ \\__\\ \\__\\\\ \\__\\ \\_______\\ \\_____ \\ \\_______\\ \\_______\\ \\__\\\\ _\\ __/ / / " println " \\|__| \\|__|\\|__|\\|__|\\|__| \\|__|\\|_______|\\|___| \\__\\|_______|\\|_______|\\|__|\\|__|\\___/ / " 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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   txt = ''; x = 0 x = x + 1; txt[0] = x; txt[x] = ' * * *****' x = x + 1; txt[0] = x; txt[x] = ' ** * * * *' x = x + 1; txt[0] = x; txt[x] = ' * * * *** *** * * *** * * * *' x = x + 1; txt[0] = x; txt[x] = ' * * * * * * ***** * * * * * *' x = x + 1; txt[0] = x; txt[x] = ' * ** ***** * * * ***** * *' x = x + 1; txt[0] = x; txt[x] = ' * * * * * * * * * * *' x = x + 1; txt[0] = x; txt[x] = ' * * *** ** * * *** * * * *' x = x + 1; txt[0] = x; txt[x] = ''   _top = '_TOP' _bot = '_BOT' txt = Banner3D(txt, isTrue()) loop ll = 1 to txt[0] say txt[ll, _top] say txt[ll, _bot] end ll   return   method Banner3D(txt, slope = '') public static   select when slope = isTrue() then nop when slope = isFalse() then nop otherwise do if slope = '' then slope = isFalse() else slope = isTrue() end end   _top = '_TOP' _bot = '_BOT' loop ll = 1 to txt[0] txt[ll, _top] = txt[ll] txt[ll, _bot] = txt[ll] txt[ll, _top] = txt[ll, _top].changestr(' ', ' ') txt[ll, _bot] = txt[ll, _bot].changestr(' ', ' ') txt[ll, _top] = txt[ll, _top].changestr('*', '///') txt[ll, _bot] = txt[ll, _bot].changestr('*', '\\\\\\') txt[ll, _top] = txt[ll, _top] || ' ' txt[ll, _bot] = txt[ll, _bot] || ' ' txt[ll, _top] = txt[ll, _top].changestr('/ ', '/\\') txt[ll, _bot] = txt[ll, _bot].changestr('\\ ', '\\/') end ll   if slope then do loop li = txt[0] to 1 by -1 ll = txt[0] - li + 1 txt[ll, _top] = txt[ll, _top].insert('', 1, li - 1, ' ') txt[ll, _bot] = txt[ll, _bot].insert('', 1, li - 1, ' ') end li end   return txt   method isTrue public constant binary returns boolean return 1 == 1   method isFalse public constant binary returns boolean return \isTrue()  
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++.
#C.2B.2B
C++
#include <iostream> #include <string> #include <boost/asio.hpp> #include <boost/regex.hpp> int main() { boost::asio::ip::tcp::iostream s("tycho.usno.navy.mil", "http"); if(!s) std::cout << "Could not connect to tycho.usno.navy.mil\n"; s << "GET /cgi-bin/timer.pl HTTP/1.0\r\n" << "Host: tycho.usno.navy.mil\r\n" << "Accept: */*\r\n" << "Connection: close\r\n\r\n" ; for(std::string line; getline(s, line); ) { boost::smatch matches; if(regex_search(line, matches, boost::regex("<BR>(.+\\s+UTC)") ) ) { std::cout << matches[1] << '\n'; break; } } }
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.
#Wren
Wren
/* window_management.wren */   var GTK_WINDOW_TOPLEVEL = 0 var GTK_ORIENTATION_VERTICAL = 1 var GTK_BUTTONBOX_CENTER = 5   foreign class GtkWindow { construct new(type) {}   foreign title=(title) foreign setDefaultSize(width, height)   foreign add(widget) foreign connectDestroy()   foreign showAll() foreign iconify() foreign deiconify() foreign maximize() foreign unmaximize() foreign move(x, y) foreign resize(width, height) foreign hide() foreign destroy() }   foreign class GtkButtonBox { construct new(orientation) {}   foreign spacing=(interval) foreign layout=(layoutStyle)   foreign add(button) }   foreign class GtkButton { construct newWithLabel(label) {}   foreign connectClicked() }   class Gdk { foreign static flush() }   class C { foreign static sleep(secs) }   var Window = GtkWindow.new(GTK_WINDOW_TOPLEVEL) Window.title = "Window management" Window.setDefaultSize(400, 400) Window.connectDestroy()   class GtkCallbacks { static btnClicked(label) { if (label == "Minimize") { Window.iconify() } else if (label == "Unminimize") { Window.deiconify() } else if (label == "Maximize") { Window.maximize() } else if (label == "Unmaximize") { Window.unmaximize() } else if (label == "Move") { Window.move(0, 0) // move to top left hand corner of display } else if (label == "Resize") { Window.resize(600, 600) } else if (label == "Hide") { Window.hide() Gdk.flush() C.sleep(5) // wait 5 seconds Window.showAll() } else if (label == "Close") { Window.destroy() } } }   var buttonBox = GtkButtonBox.new(GTK_ORIENTATION_VERTICAL) buttonBox.spacing = 20 buttonBox.layout = GTK_BUTTONBOX_CENTER Window.add(buttonBox)   var btnMin = GtkButton.newWithLabel("Minimize") btnMin.connectClicked() buttonBox.add(btnMin)   var btnUnmin = GtkButton.newWithLabel("Unminimize") btnUnmin.connectClicked() buttonBox.add(btnUnmin)   var btnMax = GtkButton.newWithLabel("Maximize") btnMax.connectClicked() buttonBox.add(btnMax)   var btnUnmax = GtkButton.newWithLabel("Unmaximize") btnUnmax.connectClicked() buttonBox.add(btnUnmax)   var btnMove = GtkButton.newWithLabel("Move") btnMove.connectClicked() buttonBox.add(btnMove)   var btnResize = GtkButton.newWithLabel("Resize") btnResize.connectClicked() buttonBox.add(btnResize)   var btnHide = GtkButton.newWithLabel("Hide") btnHide.connectClicked() buttonBox.add(btnHide)   var btnClose = GtkButton.newWithLabel("Close") btnClose.connectClicked() buttonBox.add(btnClose)   Window.showAll()
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
#C.23
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions;   namespace WordCount { class Program { static void Main(string[] args) { var text = File.ReadAllText("135-0.txt").ToLower();   var match = Regex.Match(text, "\\w+"); Dictionary<string, int> freq = new Dictionary<string, int>(); while (match.Success) { string word = match.Value; if (freq.ContainsKey(word)) { freq[word]++; } else { freq.Add(word, 1); }   match = match.NextMatch(); }   Console.WriteLine("Rank Word Frequency"); Console.WriteLine("==== ==== ========="); int rank = 1; foreach (var elem in freq.OrderByDescending(a => a.Value).Take(10)) { Console.WriteLine("{0,2} {1,-4} {2,5}", rank++, elem.Key, elem.Value); } } } }
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#Forth
Forth
16 constant w 8 constant h   : rows w * 2* ; 1 rows constant row h rows constant size   create world size allot world value old old w + value new   : init world size erase ; : age new old to new to old ;   : foreachrow ( xt -- ) size 0 do I over execute row +loop drop ;   0 constant EMPTY 1 constant HEAD 2 constant TAIL 3 constant WIRE create cstate bl c, char H c, char t c, char . c,   : showrow ( i -- ) cr old + w over + swap do I c@ cstate + c@ emit loop ; : show ['] showrow foreachrow  ;     : line ( row addr len -- ) bounds do i c@ case bl of EMPTY over c! endof 'H of HEAD over c! endof 't of TAIL over c! endof '. of WIRE over c! endof endcase 1+ loop drop ;   : load ( filename -- ) r/o open-file throw init old row + 1+ ( file row ) begin over pad 80 rot read-line throw while over pad rot line row + repeat 2drop close-file throw show cr ;     : +head ( sum i -- sum ) old + c@ HEAD = if 1+ then ; : conductor ( i WIRE -- i HEAD|WIRE ) drop 0 over 1- row - +head over row - +head over 1+ row - +head over 1- +head over 1+ +head over 1- row + +head over row + +head over 1+ row + +head 1 3 within if HEAD else WIRE then ;   \ before: empty head tail wire   create transition ' noop , ' 1+ , ' 1+ , ' conductor ,   \ after: empty tail wire head|wire   : new-state ( i -- ) dup old + c@ dup cells transition + @ execute swap new + c! ;   : newrow ( i -- ) w over + swap do I new-state loop ; : gen ['] newrow foreachrow age ;   : wireworld begin gen 0 0 at-xy show key? until ;
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
#Ruby
Ruby
require "prime"   puts Prime.each(5000).select{|p| 2.pow(p-1 ,p*p) == 1 }  
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
#Rust
Rust
// [dependencies] // primal = "0.3" // mod_exp = "1.0"   fn wieferich_primes(limit: usize) -> impl std::iter::Iterator<Item = usize> { primal::Primes::all() .take_while(move |x| *x < limit) .filter(|x| mod_exp::mod_exp(2, *x - 1, *x * *x) == 1) }   fn main() { let limit = 5000; println!("Wieferich primes less than {}:", limit); for p in wieferich_primes(limit) { println!("{}", p); } }
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Sidef
Sidef
func is_wieferich_prime(p, base=2) { powmod(base, p-1, p**2) == 1 }   say ("Wieferich primes less than 5000: ", 5000.primes.grep(is_wieferich_prime))
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
#Swift
Swift
func primeSieve(limit: Int) -> [Bool] { guard limit > 0 else { return [] } var sieve = Array(repeating: true, count: limit) sieve[0] = false if limit > 1 { sieve[1] = false } if limit > 4 { for i in stride(from: 4, to: limit, by: 2) { sieve[i] = false } } var p = 3 while true { var q = p * p if q >= limit { break } if sieve[p] { let inc = 2 * p while q < limit { sieve[q] = false q += inc } } p += 2 } return sieve }   func modpow(base: Int, exponent: Int, mod: Int) -> Int { if mod == 1 { return 0 } var result = 1 var exp = exponent var b = base b %= mod while exp > 0 { if (exp & 1) == 1 { result = (result * b) % mod } b = (b * b) % mod exp >>= 1 } return result }   func wieferichPrimes(limit: Int) -> [Int] { let sieve = primeSieve(limit: limit) var result: [Int] = [] for p in 2..<limit { if sieve[p] && modpow(base: 2, exponent: p - 1, mod: p * p) == 1 { result.append(p) } } return result }   let limit = 5000 print("Wieferich primes less than \(limit):") for p in wieferichPrimes(limit: limit) { print(p) }
http://rosettacode.org/wiki/Wieferich_primes
Wieferich primes
This page uses content from Wikipedia. The original article was at Wieferich prime. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) In number theory, a Wieferich prime is a prime number p such that p2 evenly divides 2(p − 1) − 1 . It is conjectured that there are infinitely many Wieferich primes, but as of March 2021,only two have been identified. Task Write a routine (function procedure, whatever) to find Wieferich primes. Use that routine to identify and display all of the Wieferich primes less than 5000. See also OEIS A001220 - Wieferich primes
#Wren
Wren
import "/math" for Int import "/big" for BigInt   var primes = Int.primeSieve(5000) System.print("Wieferich primes < 5000:") for (p in primes) { var num = (BigInt.one << (p - 1)) - 1 var den = p * p if (num % den == 0) System.print(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.
#Scala
Scala
import scala.swing.{ MainFrame, SimpleSwingApplication } import scala.swing.Swing.pair2Dimension   object WindowExample extends SimpleSwingApplication { def top = new MainFrame { title = "Hello!" centerOnScreen preferredSize = ((200, 150)) } }
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.
#Standard_ML
Standard ML
open XWindows ; val dp = XOpenDisplay "" ; val w = XCreateSimpleWindow (RootWindow dp) origin (Area {x=0,y=0,w=400,h=300}) 3 0 0xffffff ; XMapWindow w; XFlush dp ; XDrawString w (DefaultGC dp) (XPoint {x=10,y=50}) "Hello World!" ; XFlush dp ;
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.
#FutureBasic
FutureBasic
window 1
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.
#Gambas
Gambas
Public Sub Form_Open()   End
http://rosettacode.org/wiki/Word_wrap
Word wrap
Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. Basic task The basic task is to wrap a paragraph of text in a simple way in your language. If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns. Extra credit Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#FreeBASIC
FreeBASIC
Dim Shared As String texto, dividido()   texto = "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."   Sub Split(splitArray() As String, subject As String, delimitador As String = " ") Dim As Integer esteDelim, sgteDelim, toks Dim As String tok   Redim splitArray(toks)   Do While Strptr(subject) sgteDelim = Instr(esteDelim + 1, subject, delimitador) splitArray(toks) = Mid(subject, esteDelim + 1, sgteDelim - esteDelim - 1) If sgteDelim = FALSE Then Exit Do toks += 1 Redim Preserve splitArray(toks) esteDelim = sgteDelim Loop End Sub   Sub WordWrap(s As String, n As Integer) Split(dividido(),s," ") Dim As String fila = "" For i As Integer = 0 To Ubound(dividido) If Len(fila) = 0 Then fila = fila & dividido(i) Elseif Len(fila & " " & dividido(i)) <= n Then fila = fila & " " & dividido(i) Else Print fila fila = dividido(i) End If Next i If Len(fila) > 0 Then Print dividido(Ubound(dividido)) End Sub   Print "Ajustado a 72:" WordWrap(texto,72) Print !"\nAjustado a 80:" WordWrap(texto,80) Sleep  
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.
#Perl
Perl
#! /usr/bin/perl use strict; use XML::Mini::Document;   my @students = ( [ "April", "Bubbly: I'm > Tam and <= Emily" ], [ "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" ], [ "Emily", "Short & shrift" ] );   my $doc = XML::Mini::Document->new(); my $root = $doc->getRoot(); my $studs = $root->createChild("CharacterRemarks"); foreach my $s (@students) { my $stud = $studs->createChild("Character"); $stud->attribute("name", $s->[0]); $stud->text($s->[1]); } print $doc->toString();
http://rosettacode.org/wiki/XML/Input
XML/Input
Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath. <Students> <Student Name="April" Gender="F" DateOfBirth="1989-01-02" /> <Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" /> <Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" /> <Student Name="Dave" Gender="M" DateOfBirth="1992-07-08"> <Pet Type="dog" Name="Rover" /> </Student> <Student DateOfBirth="1993-09-10" Gender="F" Name="&#x00C9;mily" /> </Students> Expected Output April Bob Chad Dave Émily
#Neko
Neko
/** XML/Input in Neko Tectonics: nekoc xml-input.neko neko xml-input | recode html */   /* Get the Neko XML parser function */ var parse_xml = $loader.loadprim("std@parse_xml", 2);   /* Load the student.xml file as string */ var file_contents = $loader.loadprim("std@file_contents", 1); var xmlString = file_contents("students.xml");   /* Build up a (very specific) XML event processor object */ /* Needs functions for xml, done, pcdata, cdata and comment */ var events = $new(null); events.xml = function(name, attributes) { if name == "Student" { $print(attributes.Name, "\n"); } } events.done = function() { } events.pcdata = function(x) { } events.cdata = function(x) { } events.comment = function(x) { }   parse_xml(xmlString, events);   /* Entities are not converted, use external recode program for that */
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)
#Visual_Basic_.NET
Visual Basic .NET
'Example of array of 10 int types: Dim numbers As Integer() = New Integer(9) {} 'Example of array of 4 string types: Dim words As String() = {"hello", "world", "from", "mars"} 'You can also declare the size of the array and initialize the values at the same time: Dim more_numbers As Integer() = New Integer(2) {21, 14, 63}   'For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration. 'The following creates a 3x2 int matrix Dim number_matrix As Integer(,) = New Integer(2, 1) {}     'As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces. Dim string_matrix As String(,) = {{"I", "swam"}, {"in", "the"}, {"freezing", "water"}} 'or Dim funny_matrix As String(,) = New String(1, 1) {{"clowns", "are"}, {"not", "funny"}}   Dim array As Integer() = New Integer(9) {} array(0) = 1 array(1) = 3 Console.WriteLine(array(0))     'Dynamic Imports System Imports System.Collections.Generic Dim list As New List(Of Integer)() list.Add(1) list.Add(3) list(0) = 2 Console.WriteLine(list(0))
http://rosettacode.org/wiki/100_doors
100 doors
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and  toggle  the door  (if the door is closed,  open it;   if it is open,  close it). The second time, only visit every 2nd door   (door #2, #4, #6, ...),   and toggle it. The third time, visit every 3rd door   (door #3, #6, #9, ...), etc,   until you only visit the 100th door. Task Answer the question:   what state are the doors in after the last pass?   Which are open, which are closed? Alternate: As noted in this page's   discussion page,   the only doors that remain open are those whose numbers are perfect squares. Opening only those doors is an   optimization   that may also be expressed; however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
#Oberon
Oberon
MODULE Doors; IMPORT Out;   PROCEDURE Do*; (* In Oberon an asterisk after an identifier is an export mark *) CONST N = 100; len = N + 1; VAR i, j: INTEGER; closed: ARRAY len OF BOOLEAN; (* Arrays in Oberon always start with index 0; closed[0] is not used *) BEGIN FOR i := 1 TO N DO closed[i] := TRUE END; FOR i := 1 TO N DO j := 1; WHILE j < len DO IF j MOD i = 0 THEN closed[j] := ~closed[j] END; INC(j) (* ~ = NOT *) END END; (* Print a state diagram of all doors *) FOR i := 1 TO N DO IF (i - 1) MOD 10 = 0 THEN Out.Ln END; IF closed[i] THEN Out.String("- ") ELSE Out.String("+ ") END END; Out.Ln; (* Print the numbers of the open doors *) FOR i := 1 TO N DO IF ~closed[i] THEN Out.Int(i, 0); Out.Char(" ") END END; Out.Ln END Do;   END Doors.
http://rosettacode.org/wiki/Weird_numbers
Weird numbers
In number theory, a weird number is a natural number that is abundant but not semiperfect (and therefore not perfect either). In other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is abundant), but no subset of those divisors sums to the number itself (the number is not semiperfect). For example: 12 is not a weird number. It is abundant; its proper divisors 1, 2, 3, 4, 6 sum to 16 (which is > 12), but it is semiperfect, e.g.:     6 + 4 + 2 == 12. 70 is a weird number. It is abundant; its proper divisors 1, 2, 5, 7, 10, 14, 35 sum to 74 (which is > 70), and there is no subset of proper divisors that sum to 70. Task Find and display, here on this page, the first 25 weird numbers. Related tasks Abundant, deficient and perfect number classifications Proper divisors See also OEIS: A006037 weird numbers Wikipedia: weird number MathWorld: weird number
#J
J
  factor=: [: }: [: , [: */&> [: { [: <@(^ i.@>:)/"1 [: |: __&q:   classify=: 3 : 0 weird =: perfect =: deficient =: abundant =: i. 0 a=: (i. -. 0 , deficient =: 1 , i.&.:(p:inv)) y NB. a are potential semi-perfect numbers for_n. a do. if. n e. a do. factors=. factor n sf =. +/ factors if. sf < n do. deficient =: deficient , n else. if. n < sf do. abundant=: abundant , n else. perfect =: perfect , n a =: a -. (2+i.)@<.&.(%&n) y NB. remove multiples of perfect numbers continue. end. NB. compute sums of subsets to detect semiperfection NB. the following algorithm correctly finds weird numbers less than 20000 NB. remove large terms necessary for the sum to reduce the Catalan tally of sets factors =. /:~ factors NB. ascending sort NB. if the sum of the length one outfixes is less n then the factor is required in the semiperfect set. i_required =. n (1 i.~ (>(1+/\.]))) factors target =. n - +/ i_required }. factors t =. i_required {. factors NB. work in chunks of 2^16 to reduce memory requirement sp =. target e. ; (,:~2^16) <@([: +/"1 t #~ (_ ,(#t)) {. #:);.3 i. 2 ^ # t if. sp do. a =: a -. (2+i.)@<.&.(%&n) y NB. remove multiples of semi perfect numbers else. weird =: weird , n a =: a -. n end. end. end. end. a =: a -. deficient weird )  
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
#Java
Java
  import java.util.ArrayList; import java.util.List;   public class WeirdNumbers {   public static void main(String[] args) { int n = 2; // n += 2 : No odd weird numbers < 10^21 for ( int count = 1 ; count <= 25 ; n += 2 ) { if ( isWeird(n) ) { System.out.printf("w(%d) = %d%n", count, n); count++; } } }   private static boolean isWeird(int n) { List<Integer> properDivisors = getProperDivisors(n); return isAbundant(properDivisors, n) && ! isSemiPerfect(properDivisors, n); }   private static boolean isAbundant(List<Integer> divisors, int n) { int divisorSum = divisors.stream().mapToInt(i -> i.intValue()).sum(); return divisorSum > n; }   // Use Dynamic Programming private static boolean isSemiPerfect(List<Integer> divisors, int sum) { int size = divisors.size();   // The value of subset[i][j] will be true if there is a subset of divisors[0..j-1] with sum equal to i boolean subset[][] = new boolean[sum+1][size+1];   // If sum is 0, then answer is true for (int i = 0; i <= size; i++) { subset[0][i] = true; }   // If sum is not 0 and set is empty, then answer is false for (int i = 1; i <= sum; i++) { subset[i][0] = false; }   // Fill the subset table in bottom up manner for ( int i = 1 ; i <= sum ; i++ ) { for ( int j = 1 ; j <= size ; j++ ) { subset[i][j] = subset[i][j-1]; int test = divisors.get(j-1); if ( i >= test ) { subset[i][j] = subset[i][j] || subset[i - test][j-1]; } } }   return subset[sum][size]; }   private static final List<Integer> getProperDivisors(int number) { List<Integer> divisors = new ArrayList<Integer>(); long sqrt = (long) Math.sqrt(number); for ( int i = 1 ; i <= sqrt ; i++ ) { if ( number % i == 0 ) { divisors.add(i); int div = number / i; if ( div != i && div != number ) { divisors.add(div); } } } return divisors; }   }  
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
#Nim
Nim
import strutils   const nim = """ # # ##### # # ## # # ## ## # # # # # ## # # # # # # # # ## # # # # # ##### # # """ let lines = nim.dedent.multiReplace(("#", "<<<"), (" ", " "), ("< ", "<>"), ("<\n", "<>\n")).splitLines for i, line in lines: echo spaces(lines.len - i), line
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
#OCaml
OCaml
  print_string " _|_|_| _|_|_| _|_| _|_| _|_| _| _| _| _| _| _| _| _| _| _| _| _| _| _| _|_|_| _| _| _| _| _| _| _| _| _| _| _| _| _| _|_|_| _|_|_| _| _| _| _| _|_|_|_|_| "  
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++.
#Cach.C3.A9_ObjectScript
Caché ObjectScript
  Class Utils.Net [ Abstract ] {   ClassMethod ExtractHTMLData(pHost As %String = "", pPath As %String = "", pRegEx As %String = "", Output list As %List) As %Status { // implement error handling Try {   // some initialisation Set list="", sc=$$$OK   // check input parameters If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 { Set sc=$$$ERROR($$$GeneralError, "Invalid host name.") Quit }   // create http request and get page Set req=##class(%Net.HttpRequest).%New() Set req.Server=pHost Do req.Get(pPath)   // check for success If $Extract(req.HttpResponse.StatusCode)'=2 { Set sc=$$$ERROR($$$GeneralError, "Page not loaded.") Quit }   // read http response stream Set html=req.HttpResponse.Data Set html.LineTerminator=$Char(10) Set sc=html.Rewind()   // read http response stream While 'html.AtEnd { Set line=html.ReadLine(, .sc, .eol) Set pos=$Locate(line, pRegEx) If pos { Set parse=$Piece($Extract(line, pos, *), $Char(9)) Set slot=$ListLength(list)+1 Set $List(list, slot)=parse } }   } Catch err {   // an error has occurred If err.Name="<REGULAR EXPRESSION>" { Set sc=$$$ERROR($$$GeneralError, "Invalid regular expression.") } Else { Set sc=$$$ERROR($$$CacheError, $ZError) }   }   // return status Quit sc }   }  
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++.
#Ceylon
Ceylon
import ceylon.uri { parse } import ceylon.http.client { get }   shared void run() {   // apparently the cgi link is deprecated? value oldUri = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"; value newUri = "http://tycho.usno.navy.mil/timer.pl";   value contents = downloadContents(newUri); value time = extractTime(contents); print(time else "nothing found"); }   String downloadContents(String uriString) { value uri = parse(uriString); value request = get(uri); value response = request.execute(); return response.contents; }   String? extractTime(String contents) => contents .lines .filter((String element) => element.contains("UTC")) .first  ?.substring(4, 21);
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
#C.2B.2B
C++
#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <string> #include <unordered_map> #include <vector>   int main(int ac, char** av) { std::ios::sync_with_stdio(false); int head = (ac > 1) ? std::atoi(av[1]) : 10; std::istreambuf_iterator<char> it(std::cin), eof; std::filebuf file; if (ac > 2) { if (file.open(av[2], std::ios::in), file.is_open()) { it = std::istreambuf_iterator<char>(&file); } else return std::cerr << "file " << av[2] << " open failed\n", 1; } auto alpha = [](unsigned c) { return c-'A' < 26 || c-'a' < 26; }; auto lower = [](unsigned c) { return c | '\x20'; }; std::unordered_map<std::string, int> counts; std::string word; for (; it != eof; ++it) { if (alpha(*it)) { word.push_back(lower(*it)); } else if (!word.empty()) { ++counts[word]; word.clear(); } } if (!word.empty()) ++counts[word]; // if file ends w/o ws std::vector<std::pair<const std::string,int> const*> out; for (auto& count : counts) out.push_back(&count); std::partial_sort(out.begin(), out.size() < head ? out.end() : out.begin() + head, out.end(), [](auto const* a, auto const* b) { return a->second > b->second; }); if (out.size() > head) out.resize(head); for (auto const& count : out) { std::cout << count->first << ' ' << count->second << '\n'; } return 0; }  
http://rosettacode.org/wiki/Wireworld
Wireworld
Wireworld Conway's Game of Life It is capable of doing sophisticated computations with appropriate programs (it is actually Turing complete), and is much simpler to program for. A Wireworld arena consists of a Cartesian grid of cells, each of which can be in one of four states. All cell transitions happen simultaneously. The cell transition rules are this: Input State Output State Condition empty empty electron head  electron tail  electron tail  conductor conductor electron head  if 1 or 2 cells in the neighborhood of the cell are in the state “electron head” conductor conductor otherwise Task Create a program that reads a Wireworld program from a file and displays an animation of the processing. Here is a sample description file (using "H" for an electron head, "t" for a tail, "." for a conductor and a space for empty) you may wish to test with, which demonstrates two cycle-3 generators and an inhibit gate: tH......... . . ... . . Ht.. ...... While text-only implementations of this task are possible, mapping cells to pixels is advisable if you wish to be able to display large designs. The logic is not significantly more complex.
#Fortran
Fortran
program Wireworld implicit none   integer, parameter :: max_generations = 12 integer :: nrows = 0, ncols = 0, maxcols = 0 integer :: gen, ierr = 0 integer :: i, j character(1), allocatable :: cells(:,:) character(10) :: form, sub character(80) :: buff   ! open input file open(unit=8, file="wwinput.txt")   ! find numbers of rows and columns in data do read(8, "(a)", iostat=ierr) buff if(ierr /= 0) exit nrows = nrows + 1 ncols = len_trim(buff) if(ncols > maxcols) maxcols = ncols end do   ! allcate enough space to hold the data allocate(cells(0:nrows+1, 0:maxcols+1)) cells = " "   ! load data rewind(8) do i = 1, nrows read(8, "(a)", iostat=ierr) buff if(ierr /= 0) exit do j = 1, maxcols cells(i, j) = buff(j:j) end do end do close(8)   ! calculate format string for write statement write(sub, "(i8)") maxcols form = "(" // trim(adjustl(sub)) // "a1)"   do gen = 0, max_generations write(*, "(/a, i0)") "Generation ", gen do i = 1, nrows write(*, form) cells(i, 1:maxcols) end do call nextgen(cells) end do deallocate(cells)   contains   subroutine Nextgen(cells) character, intent(in out) :: cells(0:,0:) character :: buffer(0:size(cells, 1)-1, 0:size(cells, 2)-1) integer :: i, j, h   buffer = cells ! Store current status do i = 1, size(cells, 1)-2 do j = 1, size(cells, 2)-2 select case (buffer(i, j)) case(" ") ! no Change   case("H") ! If a head change to tail cells(i, j) = "t"   case("t") ! if a tail change to conductor cells(i, j) = "."   case (".") ! Count number of electron heads in surrounding eight cells. ! We can ignore that fact that we count the centre cell as ! well because we already know it contains a conductor. ! If surrounded by 1 or 2 heads change to a head h = sum(count(buffer(i-1:i+1, j-1:j+1) == "H", 1)) if(h == 1 .or. h == 2) cells(i, j) = "H" end select end do end do end subroutine Nextgen end program Wireworld
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.
#Tcl
Tcl
package provide xlib 1 package require critcl   critcl::clibraries -L/usr/X11/lib -lX11 critcl::ccode { #include <X11/Xlib.h> static Display *d; static GC gc; }   # Display connection functions critcl::cproc XOpenDisplay {Tcl_Interp* interp char* name} ok { d = XOpenDisplay(name[0] ? name : NULL); if (d == NULL) { Tcl_AppendResult(interp, "cannot open display", NULL); return TCL_ERROR; } gc = DefaultGC(d, DefaultScreen(d)); return TCL_OK; } critcl::cproc XCloseDisplay {} void { XCloseDisplay(d); }   # Basic window functions critcl::cproc XCreateSimpleWindow { int x int y int width int height int events } int { int s = DefaultScreen(d); Window w = XCreateSimpleWindow(d, RootWindow(d,s), x, y, width, height, 0, BlackPixel(d,s), WhitePixel(d,s)); XSelectInput(d, w, ExposureMask | events); return (int) w; } critcl::cproc XDestroyWindow {int w} void { XDestroyWindow(d, (Window) w); } critcl::cproc XMapWindow {int w} void { XMapWindow(d, (Window) w); } critcl::cproc XUnmapWindow {int w} void { XUnmapWindow(d, (Window) w); }   # Event receiver critcl::cproc XNextEvent {Tcl_Interp* interp} char* { XEvent e; XNextEvent(d, &e); switch (e.type) { case Expose: return "type expose"; case KeyPress: return "type key"; /* etc. This is a cheap hack version. */ default: return "type ?"; } }   # Painting functions critcl::cproc XFillRectangle {int w int x int y int width int height} void { XFillRectangle(d, (Window)w, gc, x, y, width, height); } critcl::cproc XDrawString {int w int x int y Tcl_Obj* msg} void { int len; const char *str = Tcl_GetStringFromObj(msg, &len); XDrawString(d, (Window)w, gc, x, y, str, len); }
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.
#Go
Go
package main   import ( "github.com/mattn/go-gtk/glib" "github.com/mattn/go-gtk/gtk" )   func main() { gtk.Init(nil) window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL) window.Connect("destroy", func(*glib.CallbackContext) { gtk.MainQuit() }, "") window.Show() gtk.Main() }
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.
#Groovy
Groovy
import groovy.swing.SwingBuilder new SwingBuilder().frame(title:'My Window', size:[200,100]).show()