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/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Scala
Scala
import java.io.{File, PrintWriter}   object Main extends App { val pw = new PrintWriter(new File("Flumberboozle.txt"),"UTF8"){ print("My zirconconductor short-circuited and I'm having trouble fixing this issue.\nI researched" + " online and they said that I need to connect my flumberboozle to the XKG virtual port, but I was" + " wondering if I also needed a galvanized tungsten retrothruster array? Maybe it'd help the" + " frictional radial anti-stabilizer vectronize from the flumberboozle to the XKG virtual port?") close()} }
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
#11l
11l
V GRID = ‘N D E O K G E L W’   F getwords() V words = File(‘unixdict.txt’).read().lowercase().split("\n") R words.filter(w -> w.len C 3..9)   F solve(grid, dictionary) DefaultDict[Char, Int] gridcount L(g) grid gridcount[g]++   F check_word(word) DefaultDict[Char, Int] lcount L(l) word lcount[l]++ L(l, c) lcount I c > @gridcount[l] R 1B R 0B   V mid = grid[4] R dictionary.filter(word -> @mid C word & !@check_word(word))   V chars = GRID.lowercase().split_py().join(‘’) V found = solve(chars, dictionary' getwords()) print(found.join("\n"))
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the dictionary. No word in a game can be repeated. The first word must be three or four letters long. Task Create a program to aid in the playing of the game by: Asking for contestants names. Choosing an initial random three or four letter word from the dictionary. Asking each contestant in their turn for a wordiff word. Checking the wordiff word is: in the dictionary, not a repetition of past words, and differs from the last appropriately. Optional stretch goals Add timing. Allow players to set a maximum playing time for the game. An internal timer accumulates how long each user takes to respond in their turns. Play is halted if the maximum playing time is exceeded on a players input. That last player must have entered a wordiff or loses. If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Julia
Julia
isoneless(nw, ow) = any(i -> nw == ow[begin:i-1] * ow[i+1:end], eachindex(ow)) isonemore(nw, ow) = isoneless(ow, nw) isonechanged(x, y) = length(x) == length(y) && count(i -> x[i] != y[i], eachindex(y)) == 1 onefrom(nw, ow) = isoneless(nw, ow) || isonemore(nw, ow) || isonechanged(nw, ow)   function askprompt(prompt) ans = "" while isempty(ans) print(prompt) ans = strip(readline()) end return ans end   function wordiff(dictfile = "unixdict.txt") wordlist = [w for w in split(read(dictfile, String), r"\s+") if !occursin(r"\W", w) && length(w) > 2] starters = [w for w in wordlist if 3 <= length(w) <= 4]   timelimit = something(tryparse(Float64, askprompt("Time limit (min) or 0 for none: ")), 0.0)   players = split(askprompt("Enter players' names. Separate by commas: "), r"\s*,\s*") times, word = Dict(player => Float32[] for player in players), rand(starters) used, totalsecs, timestart = [word], timelimit * 60, time() while length(players) > 1 player = popfirst!(players) playertimestart = time() newword = askprompt("$player, your move. The current word is $word. Your worddiff? ") if timestart + totalsecs > time() if onefrom(newword, word) && !(newword in used) && lowercase(newword) in wordlist println("Correct.") push!(players, player) word = newword push!(used, newword) push!(times[player], time() - playertimestart) else println("Wordiff choice incorrect. Player $player exits game.") end else # out of time println("Sorry, time was up. Timing ranks for remaining players:") avtimes = Dict(p => isempty(times[p]) ? NaN : sum(times[p]) / length(times[p]) for p in players) sort!(players, lt = (x, y) -> avtimes[x] < avtimes[y]) foreach(p -> println(" $p:", lpad(avtimes[p], 10), " seconds average"), players) break end sleep(rand() * 3) end length(players) < 2 && println("Player $(first(players)) is the only one left, and wins the game.") end   wordiff()  
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the dictionary. No word in a game can be repeated. The first word must be three or four letters long. Task Create a program to aid in the playing of the game by: Asking for contestants names. Choosing an initial random three or four letter word from the dictionary. Asking each contestant in their turn for a wordiff word. Checking the wordiff word is: in the dictionary, not a repetition of past words, and differs from the last appropriately. Optional stretch goals Add timing. Allow players to set a maximum playing time for the game. An internal timer accumulates how long each user takes to respond in their turns. Play is halted if the maximum playing time is exceeded on a players input. That last player must have entered a wordiff or loses. If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Nim
Nim
import httpclient, sequtils, sets, strutils, sugar from unicode import capitalize   const DictFname = "unixdict.txt" DictUrl1 = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" # ~25K words DictUrl2 = "https://raw.githubusercontent.com/dwyl/english-words/master/words.txt" # ~470K words     type Dictionary = HashSet[string]     proc loadDictionary(fname = DictFname): Dictionary = ## Return appropriate words from a dictionary file. for word in fname.lines(): if word.len >= 3 and word.allCharsInSet(Letters): result.incl word.toLowerAscii     proc loadWebDictionary(url: string): Dictionary = ## Return appropriate words from a dictionary web page. let client = newHttpClient() for word in client.getContent(url).splitLines(): if word.len >= 3 and word.allCharsInSet(Letters): result.incl word.toLowerAscii     proc getPlayers(): seq[string] = ## Return inputted ordered list of contestant names. try: stdout.write "Space separated list of contestants: " stdout.flushFile() result = stdin.readLine().splitWhitespace().map(capitalize) if result.len == 0: quit "Empty list of names. Quitting.", QuitFailure except EOFError: echo() quit "Encountered end of file. Quitting.", QuitFailure     proc isWordiffRemoval(word, prev: string; comment = true): bool = ## Is "word" derived from "prev" by removing one letter? for i in 0..prev.high: if word == prev[0..<i] & prev[i+1..^1]: return true if comment: echo "Word is not derived from previous by removal of one letter." result = false     proc isWordiffInsertion(word, prev: string; comment = true): bool = ## Is "word" derived from "prev" by adding one letter? for i in 0..word.high: if prev == word[0..<i] & word[i+1..^1]: return true if comment: echo "Word is not derived from previous by insertion of one letter." return false     proc isWordiffChange(word, prev: string; comment = true): bool = ## Is "word" derived from "prev" by changing exactly one letter? var diffcount = 0 for i in 0..word.high: diffcount += ord(word[i] != prev[i]) if diffcount != 1: if comment: echo "More or less than exactly one character changed." return false result = true     proc isWordiff(word: string; wordiffs: seq[string]; dict: Dictionary; comment = true): bool = ## Is "word" a valid wordiff from "wordiffs[^1]"? if word notin dict: if comment: echo "That word is not in my dictionary." return false if word in wordiffs: if comment: echo "That word was already used." return false result = if word.len < wordiffs[^1].len: word.isWordiffRemoval(wordiffs[^1], comment) elif word.len > wordiffs[^1].len: word.isWordiffInsertion(wordiffs[^1], comment) else: word.isWordiffChange(wordiffs[^1], comment)     proc couldHaveGot(wordiffs: seq[string]; dict: Dictionary): seq[string] = for word in dict - wordiffs.toHashSet: if word.isWordiff(wordiffs, dict, comment = false): result.add word     when isMainModule: import random   randomize() let dict = loadDictionary(DictFname) let dict34 = collect(newSeq): for word in dict: if word.len in [3, 4]: word let start = sample(dict34) var wordiffs = @[start] let players = getPlayers() var iplayer = 0 var word: string while true: let name = players[iplayer] while true: stdout.write "$1, input a wordiff from “$2”: ".format(name, wordiffs[^1]) stdout.flushFile() try: word = stdin.readLine().strip() if word.len > 0: break except EOFError: quit "Encountered end of file. Quitting.", QuitFailure if word.isWordiff(wordiffs, dict): wordiffs.add word else: echo "You have lost, $#.".format(name) let possibleWords = couldHaveGot(wordiffs, dict) if possibleWords.len > 0: echo "You could have used: ", possibleWords[0..min(possibleWords.high, 20)].join(" ") break iplayer = (iplayer + 1) mod players.len
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.
#C.23
C#
  public class Line { private double x0, y0, x1, y1; private Color foreColor; private byte lineStyleMask; private int thickness; private float globalm;   public Line(double x0, double y0, double x1, double y1, Color color, byte lineStyleMask, int thickness) { this.x0 = x0; this.y0 = y0; this.y1 = y1; this.x1 = x1;   this.foreColor = color;   this.lineStyleMask = lineStyleMask;   this.thickness = thickness;   }   private void plot(Bitmap bitmap, double x, double y, double c) { int alpha = (int)(c * 255); if (alpha > 255) alpha = 255; if (alpha < 0) alpha = 0; Color color = Color.FromArgb(alpha, foreColor); if (BitmapDrawHelper.checkIfInside((int)x, (int)y, bitmap)) { bitmap.SetPixel((int)x, (int)y, color); } }   int ipart(double x) { return (int)x;}   int round(double x) {return ipart(x+0.5);}   double fpart(double x) { if(x<0) return (1-(x-Math.Floor(x))); return (x-Math.Floor(x)); }   double rfpart(double x) { return 1-fpart(x); }     public void draw(Bitmap bitmap) { bool steep = Math.Abs(y1-y0)>Math.Abs(x1-x0); double temp; if(steep){ temp=x0; x0=y0; y0=temp; temp=x1;x1=y1;y1=temp; } if(x0>x1){ temp = x0;x0=x1;x1=temp; temp = y0;y0=y1;y1=temp; }   double dx = x1-x0; double dy = y1-y0; double gradient = dy/dx;   double xEnd = round(x0); double yEnd = y0+gradient*(xEnd-x0); double xGap = rfpart(x0+0.5); double xPixel1 = xEnd; double yPixel1 = ipart(yEnd);   if(steep){ plot(bitmap, yPixel1, xPixel1, rfpart(yEnd)*xGap); plot(bitmap, yPixel1+1, xPixel1, fpart(yEnd)*xGap); }else{ plot(bitmap, xPixel1,yPixel1, rfpart(yEnd)*xGap); plot(bitmap, xPixel1, yPixel1+1, fpart(yEnd)*xGap); } double intery = yEnd+gradient;   xEnd = round(x1); yEnd = y1+gradient*(xEnd-x1); xGap = fpart(x1+0.5); double xPixel2 = xEnd; double yPixel2 = ipart(yEnd); if(steep){ plot(bitmap, yPixel2, xPixel2, rfpart(yEnd)*xGap); plot(bitmap, yPixel2+1, xPixel2, fpart(yEnd)*xGap); }else{ plot(bitmap, xPixel2, yPixel2, rfpart(yEnd)*xGap); plot(bitmap, xPixel2, yPixel2+1, fpart(yEnd)*xGap); }   if(steep){ for(int x=(int)(xPixel1+1);x<=xPixel2-1;x++){ plot(bitmap, ipart(intery), x, rfpart(intery)); plot(bitmap, ipart(intery)+1, x, fpart(intery)); intery+=gradient; } }else{ for(int x=(int)(xPixel1+1);x<=xPixel2-1;x++){ plot(bitmap, x,ipart(intery), rfpart(intery)); plot(bitmap, x, ipart(intery)+1, fpart(intery)); intery+=gradient; } } } }  
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libxml/parser.h> #include <libxml/tree.h>   const char *names[] = { "April", "Tam O'Shanter", "Emily", NULL }; const char *remarks[] = { "Bubbly: I'm > Tam and <= Emily", "Burns: \"When chapman billies leave the street ...\"", "Short & shrift", NULL };   int main() { xmlDoc *doc = NULL; xmlNode *root = NULL, *node; const char **next; int a;   doc = xmlNewDoc("1.0"); root = xmlNewNode(NULL, "CharacterRemarks"); xmlDocSetRootElement(doc, root);   for(next = names, a = 0; *next != NULL; next++, a++) { node = xmlNewNode(NULL, "Character"); (void)xmlNewProp(node, "name", *next); xmlAddChild(node, xmlNewText(remarks[a])); xmlAddChild(root, node); }   xmlElemDump(stdout, doc, root);   xmlFreeDoc(doc); xmlCleanupParser();   return EXIT_SUCCESS; }
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
#Bracmat
Bracmat
( :?names & ( get$("students.xml",X,ML)  :  ? ( ( Student . (? (Name.?name) ?,) | ? (Name.?name) ? ) & !names !name:?names & ~ )  ? | !names ) )
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)
#Simula
Simula
BEGIN   PROCEDURE STATIC; BEGIN INTEGER ARRAY X(0:4);   X(0) := 10; X(1) := 11; X(2) := 12; X(3) := 13; X(4) := X(0);   OUTTEXT("STATIC AT 4: "); OUTINT(X(4), 0); OUTIMAGE END STATIC;   PROCEDURE DYNAMIC(N); INTEGER N; BEGIN INTEGER ARRAY X(0:N-1);   X(0) := 10; X(1) := 11; X(2) := 12; X(3) := 13; X(4) := X(0);   OUTTEXT("DYNAMIC AT 4: "); OUTINT(X(4),0); OUTIMAGE END DYNAMIC;   STATIC; DYNAMIC(5) END ARRAYS.  
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#J
J
require'stats' outcome=: 3 0,1 1,:0 3 pairs=: (i.4) e."1(2 comb 4) standings=: +/@:>&>,{<"1<"1((i.4) e."1 pairs)#inv"1/ outcome
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Java
Java
import java.util.Arrays;   public class GroupStage{ //team left digit vs team right digit static String[] games = {"12", "13", "14", "23", "24", "34"}; static String results = "000000";//start with left teams all losing   private static boolean nextResult(){ if(results.equals("222222")) return false; int res = Integer.parseInt(results, 3) + 1; results = Integer.toString(res, 3); while(results.length() < 6) results = "0" + results; //left pad with 0s return true; }   public static void main(String[] args){ int[][] points = new int[4][10]; //playing 3 games, points range from 0 to 9 do{ int[] records = {0,0,0,0}; for(int i = 0; i < 6; i++){ switch(results.charAt(i)){ case '2': records[games[i].charAt(0) - '1'] += 3; break; //win for left team case '1': //draw records[games[i].charAt(0) - '1']++; records[games[i].charAt(1) - '1']++; break; case '0': records[games[i].charAt(1) - '1'] += 3; break; //win for right team } } Arrays.sort(records); //sort ascending, first place team on the right points[0][records[0]]++; points[1][records[1]]++; points[2][records[2]]++; points[3][records[3]]++; }while(nextResult()); System.out.println("First place: " + Arrays.toString(points[3])); System.out.println("Second place: " + Arrays.toString(points[2])); System.out.println("Third place: " + Arrays.toString(points[1])); System.out.println("Fourth place: " + Arrays.toString(points[0])); } }
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#J
J
require 'files' NB. for fwrites   x =. 1 2 3 1e11 y =.  %: x NB. y is sqrt(x)   xprecision =. 3 yprecision =. 5   filename =. 'whatever.txt'   data =. (0 j. xprecision,yprecision) ": x,.y   data fwrites filename
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.
#Java
Java
import java.io.*;   public class FloatArray { public static void writeDat(String filename, double[] x, double[] y, int xprecision, int yprecision) throws IOException { assert x.length == y.length; PrintWriter out = new PrintWriter(filename); for (int i = 0; i < x.length; i++) out.printf("%."+xprecision+"g\t%."+yprecision+"g\n", x[i], y[i]); out.close(); }   public static void main(String[] args) { double[] x = {1, 2, 3, 1e11}; double[] y = new double[x.length]; for (int i = 0; i < x.length; i++) y[i] = Math.sqrt(x[i]);   try { writeDat("sqrt.dat", x, y, 3, 5); } catch (IOException e) { System.err.println("writeDat: exception: "+e); }   try { BufferedReader br = new BufferedReader(new FileReader("sqrt.dat")); String line; while ((line = br.readLine()) != null) System.out.println(line); } catch (IOException e) { } } }
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
n=100; tmp=ConstantArray[-1,n]; Do[tmp[[i;;;;i]]*=-1;,{i,n}]; Do[Print["door ",i," is ",If[tmp[[i]]==-1,"closed","open"]],{i,1,Length[tmp]}]
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Nim
Nim
import xmldom   var dom = getDOM() document = dom.createDocument("", "root") topElement = document.documentElement firstElement = document.createElement "element" textNode = document.createTextNode "Some text here"   topElement.appendChild firstElement firstElement.appendChild textNode   echo document
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Objeck
Objeck
use XML;   bundle Default { class Test { function : Main(args : String[]) ~ Nil { builder := XMLBuilder->New("root", "1.0"); root := builder->GetRoot(); element := XMLElement->New(XMLElementType->ELEMENT, "element", "Some text here"); root->AddChild(element); builder->ToString()->PrintLine(); } } }
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
#BASIC
BASIC
10 S$ = "BASIC" : REM OUR LANGUAGE NAME 20 DIM B(5,5) : REM OUR BIGMAP CHARACTERS 30 FOR L = 1 TO 5 : REM 5 CHARACTERS 40 FOR M = 1 TO 5 : REM 5 ROWS 50 READ B(L,M) 60 NEXT M, L   100 GR : REM BLACK BACKGROUND 110 COLOR = 1 : REM OUR SHADOW WILL BE RED 120 HOME : REM CLS 130 R = 9 : REM SHADOW WILL START ON ROW 5 140 C = 2 : REM SHADOW WILL START AT COLUMN 2 150 GOSUB 2000"DRAW SHADOW 160 COLOR = 13 : REM OUR FOREGROUND WILL BE YELLOW 170 R = 10 : REM FOREGROUND WILL START ON ROW 6 180 C = 3 : REM FOREGROUND WILL START ON COLUMN 3 190 GOSUB 2000"DISPLAY THE LANGUAGE NAME   999 STOP   1000 REM CONVERT TO BINARY BIGMAP 1010 T = N : REM TEMPORARY VARIABLE 1020 G$ = "" : REM THIS WILL CONTAIN OUR 5 CHARACTER BINARY BIGMAP 1040 FOR Z = 5 TO 0 STEP -1 1050 D$ = " " : REM ASSUME NEXT DIGIT IS ZERO (DRAW A SPACE) 1055 S = 2 ^ Z 1060 IF T >= S THEN D$ = "*" : T = T - S : REM IS A BLOCK 1070 G$ = G$ + D$ 1080 NEXT Z 1090 RETURN   2000 REM DISPLAY THE BIG LETTERS 2010 FOR L = 1 TO 5 : REM OUR 5 ROWS 2020 X = C : Y = R + L - 1 : REM PRINT AT R+L-1,C; 2030 FOR M = 1 TO 5 : REM BIGMAP FOR EACH CHARACTER 2040 N = B(M, L) 2050 GOSUB 1000 2060 FOR I = 1 TO LEN(G$) : IF MID$(G$, I, 1) <> " " THEN PLOT X,Y :REM 5 CHARACTER BIGMAP 2070 X = X + 1 : NEXT I 2080 X = X + 1 : REM PRINT " ";: REM SPACE BETWEEN EACH LETTER 2090 NEXT M, L 2100 RETURN   9000 DATA 30,17,30,17,30: REM B 9010 DATA 14,17,31,17,17: REM A 9020 DATA 15,16,14,1,30: REM S 9030 DATA 31,4,4,4,31: REM I 9040 DATA 14,17,16,17,14: REM C  
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#SenseTalk
SenseTalk
put "New String" into file "~/Desktop/myFile.txt"
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Sidef
Sidef
var file = File(__FILE__) file.open_w(\var fh, \var err) || die "Can't open #{file}: #{err}" fh.print("Hello world!") || die "Can't write to #{file}: #{$!}"
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Smalltalk
Smalltalk
'file.txt' asFilename contents:'Hello World'
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
#8080_Assembly
8080 Assembly
puts: equ 9 ; CP/M syscall to print string fopen: equ 15 ; CP/M syscall to open a file fread: equ 20 ; CP/M syscall to read from file FCB1: equ 5Ch ; First FCB (input file) DTA: equ 80h ; Disk transfer address org 100h ;;; Make wheel (2nd argument) lowercase and store it lxi d,DTA+1 ; Start of command line arguments scan: inr e ; Scan until we find a space rz ; Stop if not found in 128 bytes ldax d cpi ' ' ; Found it? jnz scan ; If not, try again inx d ; If so, wheel starts 1 byte onwards lxi h,wheel ; Space for wheel lxi b,920h ; B=9 (chars), C=20 (case bit) whlcpy: ldax d ; Get wheel character ora c ; Make lowercase mov m,a ; Store inx d ; Increment both pointers inx h dcr b ; Decrement counter jnz whlcpy ; While not zero, copy next character ;;; Open file in FCB1 mvi e,FCB1 ; D is already 0 mvi c,fopen call 5 ; Returns A=FF on error inr a ; If incrementing A gives zero, jz err ; then print error and stop lxi h,word ; Copy into word ;;; Read a 128-byte block from the file block: push h ; Keep word pointer lxi d,FCB1 ; Read from file mvi c,fread call 5 pop h ; Restore word pointer dcr a ; A=1 = EOF rz ; If so, stop. inr a ; Otherwise, A<>0 = error jnz err lxi d,DTA ; Start reading at DTA char: ldax d ; Get character mov m,a ; Store in word cpi 26 ; EOF reached? rz ; Then stop cpi 10 ; End of line reached? jz ckword ; Then we have a full word inx h ; Increment word pointer nxchar: inr e ; Increment DTA pointer (low byte) jz block ; If rollover, get next block jmp char ; Otherwise, handle next character in block ;;; Check if current word is valid ckword: push d ; Keep block pointer lxi d,wheel ; Copy the wheel lxi h,wcpy mvi c,9 ; 9 characters cpyw: ldax d ; Get character mov m,a ; Store in copy inx h ; Increment pointers inx d dcr c ; Decrement counters jnz cpyw ; Done yet? lxi d,word ; Read from current word wrdch: ldax d ; Get character cpi 32 ; Check if <32 jc wdone ; If so, the word is done lxi h,wcpy ; Check against the wheel letters mvi b,9 wlch: cmp m ; Did we find it? jz findch inx h ; If not, try next character in wheel dcr b ; As long as there are characters jnz wlch ; If no match, this word is invalid wnext: pop d ; Restore block pointer lxi h,word ; Start reading new word jmp nxchar ; Continue with character following word findch: mvi m,0 ; Found a match - set char to 0 inx d ; And look at next character in word jmp wrdch wdone: lda wcpy+4 ; Word is done - check if middle char used ana a ; If not, the word is invalid jnz wnext lxi h,wcpy ; See how many characters used lxi b,9 ; C=9 (counter), B=0 (used) whtest: mov a,m ; Get wheel character ana a ; Is it zero? jnz $+4 ; If not, skip next instr inr b ; If so, count it inx h ; Next wheel character dcr c ; Decrement counter jnz whtest mvi a,2 ; At least 3 characters must be used cmp b jnc wnext ; If not, the word is invalid xchg ; If so, the word _is_ valid, pointer in HL mvi m,13 ; add CR inx h mvi m,10 ; and LF inx h mvi m,'$' ; and the CP/M string terminator lxi d,word ; Then print the word mvi c,puts call 5 jmp wnext err: lxi d,errs ; Print file error mvi c,puts jz 5 errs: db 'File error$' ; Error message wheel: ds 9 ; Room for wheel wcpy: ds 9 ; Copy of wheel (to mark characters used) word: equ $ ; Room for current word
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
#APL
APL
wordwheel←{ words←((~∊)∘⎕TC⊆⊢) 80 ¯1⎕MAP ⍵ match←{ 0=≢⍵:1 ~(⊃⍵)∊⍺:0 ⍺[(⍳⍴⍺)~⍺⍳⊃⍵]∇1↓⍵ } middle←(⌈0.5×≢)⊃⊢ words←((middle ⍺)∊¨words)/words words←(⍺∘match¨words)/words (⍺⍺≤≢¨words)/words }
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the dictionary. No word in a game can be repeated. The first word must be three or four letters long. Task Create a program to aid in the playing of the game by: Asking for contestants names. Choosing an initial random three or four letter word from the dictionary. Asking each contestant in their turn for a wordiff word. Checking the wordiff word is: in the dictionary, not a repetition of past words, and differs from the last appropriately. Optional stretch goals Add timing. Allow players to set a maximum playing time for the game. An internal timer accumulates how long each user takes to respond in their turns. Play is halted if the maximum playing time is exceeded on a players input. That last player must have entered a wordiff or loses. If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Phix
Phix
-- demo\rosetta\Wordiff.exw include pGUI.e Ihandle dlg, playerset, playtime, current, remain, turn, input, help, quit, hframe, history, timer atom t0, t1, t=0 constant title = "Wordiff game", help_text = """ Allows single or multi-player modes. Enter eg "Pete" to play every round yourself, "Computer" for the computer to play itself, "Pete,Computer" (or vice versa) to play against the computer, "Pete,Sue" for a standard two-payer game, or "Pete,Computer,Sue,Computer" for auto-plays between each human. Words must be 3 letters or more, and present in the dictionary, and not already used. You must key return (not tab) to finish entering your move. The winner is the fastest average time, if the timer is running (/non-zero), otherwise play continues until player elimination leaves one (or less) remaining. NB: Pressing tab or clicking on help will restart or otherwise mess up the gameplay. """ function help_cb(Ihandln /*ih*/) IupMessage(title,help_text) IupSetFocus(dlg) return IUP_DEFAULT end function function over2(string word) return length(word)>2 end function function less5(string word) return length(word)<5 end function sequence words = filter(unix_dict(),over2), valid = {}, used = {} string word integer lw sequence players, eliminated, times, averages integer player function levenshtein1(string w) bool res = false integer l = length(w) if not find(w,used) and abs(l-lw)<=1 then sequence costs = tagset(l+1,0) for i=1 to lw do costs[1] = i integer newcost = i-1, pj = i for j=1 to l do integer cj = costs[j+1], ne = word[i]!=w[j], nc = newcost+ne pj = min({pj+1, cj+1, nc}) costs[j+1] = pj newcost = cj end for end for res = costs[$-1]==1 end if return res end function procedure game_over() IupSetAttribute(history,"APPENDITEM","GAME OVER:") if length(valid) then string valids = "You could have had "&join(valid,", ") IupSetAttribute(history,"APPENDITEM",valids) end if string winner = "nobody" atom best = -1 for i=1 to length(players) do string player = players[i], msg if eliminated[i] then msg = ": eliminated" else atom average = averages[i] if average=-1 then msg = ": no times" else msg = sprintf(": %.3f",average) if best=-1 or average<best then winner = player best = average end if end if end if IupSetAttribute(history,"APPENDITEM",player&msg) end for IupSetAttribute(history,"APPENDITEM","And the winner is: "&winner) IupSetInt(history,"TOPITEM",IupGetInt(history,"COUNT")) IupSetInt(timer,"RUN",false) end procedure procedure score(string move) times[player] = append(times[player],time()-t1) averages[player] = sum(times[player])/length(times[player]) used = append(used,move) word = move lw = length(word) valid = filter(words,levenshtein1) IupSetStrAttribute(current,"TITLE","Current word: "&word) end procedure procedure advance_player() while true do player = mod(player,length(players))+1 if not eliminated[player] then exit end if end while IupSetStrAttribute(turn,"TITLE",players[player]&"'s turn:") IupRefreshChildren(turn) IupSetStrAttribute(input,"VALUE",word) t1 = time() end procedure procedure autoplay() while true do if length(valid)=0 then IupSetAttribute(history,"APPENDITEM","no more moves possible") game_over() exit end if if proper(players[player])!="Computer" then exit end if string move = valid[rand(length(valid))] IupSetStrAttribute(history,"APPENDITEM","%s's move: %s\n", {players[player],move}) IupSetInt(history,"TOPITEM",IupGetInt(history,"COUNT")) score(move) advance_player() end while end procedure procedure new_game(bool bStart=true) bool bActive = length(players)!=0 IupSetInt(turn,"ACTIVE",bActive) IupSetInt(input,"ACTIVE",bActive) if bActive and bStart then sequence w34 = filter(words,less5) while true do integer r = rand(length(w34)) word = w34[r] lw = length(word) used = {word} valid = filter(words,levenshtein1) if length(valid)!=0 then exit end if w34[r..r] = {} end while IupSetStrAttribute(current,"TITLE","Current word: "&word) IupSetStrAttribute(turn,"TITLE",players[player]&"'s turn:") IupRefreshChildren(turn) IupSetStrAttribute(input,"VALUE",word) IupSetAttribute(history,"REMOVEITEM","ALL") IupSetAttribute(history,"APPENDITEM","Initial word: "&word) IupSetInt(history,"TOPITEM",IupGetInt(history,"COUNT")) integer l = length(players) eliminated = repeat(false,l) times = repeat({},l) averages = repeat(-1,l) t0 = time() t1 = time() IupSetInt(timer,"RUN",t!=0) autoplay() end if end procedure function players_cb(Ihandln /*playerset*/) players = split(IupGetAttribute(playerset,"VALUE"),",") player = 1 new_game(false) return IUP_DEFAULT end function function playtime_cb(Ihandle /*playtime*/) t = IupGetInt(playtime, "VALUE") if t then IupSetInt(remain,"VISIBLE",true) IupSetStrAttribute(remain,"TITLE","Remaining: %.1fs",{t}) else IupSetInt(remain,"VISIBLE",false) end if IupRefreshChildren(remain) return IUP_DEFAULT end function function focus_cb(Ihandle /*input*/) new_game(true) return IUP_DEFAULT end function procedure verify_move() string move = IupGetAttribute(input,"VALUE"), okstr = "ok" bool ok = not find(move,used) if not ok then okstr = "already used" else ok = find(move,words) if not ok then okstr = "not in dictionary" else ok = find(move,valid) if not ok then okstr = "more than one change" else used = append(used,move) end if end if end if if not ok then okstr &= ", player eliminated" end if IupSetStrAttribute(history,"APPENDITEM","%s's move: %s %s\n", {players[player],move,okstr}) IupSetInt(history,"TOPITEM",IupGetInt(history,"COUNT")) if not ok then eliminated[player] = true if length(players)-sum(eliminated)<=1 then game_over() return end if else score(move) end if advance_player() autoplay() end procedure function timer_cb(Ihandle /*timer*/) atom e = time()-t0 if e>=t then IupSetStrAttribute(remain,"TITLE","Remaining: 0s") IupSetInt(turn,"ACTIVE",false) IupSetInt(input,"ACTIVE",false) game_over() else IupSetStrAttribute(remain,"TITLE","Remaining: %.1fs",{t-e}) end if return IUP_DEFAULT end function function quit_cb(Ihandle /*ih*/) return IUP_CLOSE end function function key_cb(Ihandle /*dlg*/, atom c) if c=K_ESC then return IUP_CLOSE elsif c=K_CR then Ihandln focus = IupGetFocus() if focus=playerset then IupSetFocus(playtime) elsif focus=playtime then IupSetFocus(input) new_game() elsif focus=input then verify_move() end if elsif c=K_F1 then return help_cb(NULL) elsif c=K_cC then integer n = IupGetInt(history,"COUNT") sequence hist = repeat(0,n) for i=1 to n do hist[i] = IupGetAttributeId(history,"",i) end for hist = join(hist,"\n") Ihandln clip = IupClipboard() IupSetAttribute(clip,"TEXT",hist) clip = IupDestroy(clip) end if return IUP_CONTINUE end function IupOpen() playerset = IupText(`EXPAND=HORIZONTAL`) playtime = IupText(`SPIN=Yes, SPINMIN=0, RASTERSIZE=48x`) IupSetCallback({playerset,playtime},"KILLFOCUS_CB",Icallback("players_cb")) IupSetCallback(playtime,"VALUECHANGED_CB",Icallback("playtime_cb")) turn = IupLabel("turn","ACTIVE=NO") input = IupText("EXPAND=HORIZONTAL, ACTIVE=NO") IupSetCallback(input,"GETFOCUS_CB",Icallback("focus_cb")) current = IupLabel("Current word:","EXPAND=HORIZONTAL") remain = IupLabel("Remaining time:0s","VISIBLE=NO") history = IupList("VISIBLELINES=10, EXPAND=YES, CANFOCUS=NO") hframe = IupFrame(history,"TITLE=History, PADDING=5x4") help = IupButton("Help (F1)",Icallback("help_cb"),"PADDING=5x4") quit = IupButton("Close", Icallback("quit_cb")) timer = IupTimer(Icallback("timer_cb"),100,false) sequence buttons = {IupFill(),help,IupFill(),quit,IupFill()} constant acp = "ALIGNMENT=ACENTER, PADDING=5" Ihandle settings = IupHbox({IupLabel("Contestant name(s)"), playerset, IupLabel("Timer (seconds)"), playtime},acp), currbox = IupHbox({current,remain},acp), numbox = IupHbox({turn,input},acp), btnbox = IupHbox(buttons,"PADDING=40, NORMALIZESIZE=BOTH"), vbox = IupVbox({settings, currbox, numbox, hframe, btnbox}, "GAP=5,MARGIN=5x5") dlg = IupDialog(vbox, `TITLE="%s", SIZE=500x220`, {title}) IupSetCallback(dlg, "K_ANY", Icallback("key_cb")) IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if
http://rosettacode.org/wiki/Xiaolin_Wu%27s_line_algorithm
Xiaolin Wu's line algorithm
Task Implement the   Xiaolin Wu's line algorithm   described in Wikipedia. This algorithm draws anti-aliased lines. Related task   See   Bresenham's line algorithm   for aliased lines.
#D
D
import std.math, std.algorithm, grayscale_image;   /// Plots anti-aliased line by Xiaolin Wu's line algorithm. void aaLine(Color)(ref Image!Color img, double x1, double y1, double x2, double y2, in Color color) pure nothrow @safe @nogc { // Straight translation of Wikipedia pseudocode.   // std.math.round is not pure. ** static double round(in double x) pure nothrow @safe @nogc { return floor(x + 0.5); }   static double fpart(in double x) pure nothrow @safe @nogc { return x - x.floor; }   static double rfpart(in double x) pure nothrow @safe @nogc { return 1 - fpart(x); }   auto dx = x2 - x1; auto dy = y2 - y1; immutable ax = dx.abs; immutable ay = dy.abs;   static Color mixColors(in Color c1, in Color c2, in double p) pure nothrow @safe @nogc { static if (is(Color == RGB)) return Color(cast(ubyte)(c1.r * p + c2.r * (1 - p)), cast(ubyte)(c1.g * p + c2.g * (1 - p)), cast(ubyte)(c1.b * p + c2.b * (1 - p))); else // This doesn't work for every kind of Color. return Color(cast(ubyte)(c1 * p + c2 * (1 - p))); }   // Plot function set here to handle the two cases of slope. void function(ref Image!Color, in int, in int, in double, in Color) pure nothrow @safe @nogc plot;   if (ax < ay) { swap(x1, y1); swap(x2, y2); swap(dx, dy); //plot = (img, x, y, p, col) { plot = (ref img, x, y, p, col) { assert(p >= 0.0 && p <= 1.0); img[y, x] = mixColors(col, img[y, x], p); }; } else { //plot = (img, x, y, p, col) { plot = (ref img, x, y, p, col) { assert(p >= 0.0 && p <= 1.0); img[x, y] = mixColors(col, img[x, y], p); }; }   if (x2 < x1) { swap(x1, x2); swap(y1, y2); } immutable gradient = dy / dx;   // Handle first endpoint. auto xEnd = round(x1); auto yEnd = y1 + gradient * (xEnd - x1); auto xGap = rfpart(x1 + 0.5); // This will be used in the main loop. immutable xpxl1 = cast(int)xEnd; immutable ypxl1 = cast(int)yEnd.floor; plot(img, xpxl1, ypxl1, rfpart(yEnd) * xGap, color); plot(img, xpxl1, ypxl1 + 1, fpart(yEnd) * xGap, color); // First y-intersection for the main loop. auto yInter = yEnd + gradient;   // Handle second endpoint. xEnd = round(x2); yEnd = y2 + gradient * (xEnd - x2); xGap = fpart(x2 + 0.5); // This will be used in the main loop. immutable xpxl2 = cast(int)xEnd; immutable ypxl2 = cast(int)yEnd.floor; plot(img, xpxl2, ypxl2, rfpart(yEnd) * xGap, color); plot(img, xpxl2, ypxl2 + 1, fpart(yEnd) * xGap, color);   // Main loop. foreach (immutable x; xpxl1 + 1 .. xpxl2) { plot(img, x, cast(int)yInter.floor, rfpart(yInter), color); plot(img, x, cast(int)yInter.floor + 1, fpart(yInter), color); yInter += gradient; } }   void main() { auto im1 = new Image!Gray(400, 300); im1.clear(Gray.white); im1.aaLine(7.4, 12.3, 307, 122.5, Gray.black); im1.aaLine(177.4, 12.3, 127, 222.5, Gray.black); im1.savePGM("xiaolin_lines1.pgm");   auto im2 = new Image!RGB(400, 300); im2.clear(RGB(0, 255, 0)); immutable red = RGB(255, 0, 0); im2.aaLine(7.4, 12.3, 307, 122.5, red); im2.aaLine(177.4, 12.3, 127, 222.5, red); im2.savePPM6("xiaolin_lines2.ppm"); }
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq;   class Program { static string CreateXML(Dictionary<string, string> characterRemarks) { var remarks = characterRemarks.Select(r => new XElement("Character", r.Value, new XAttribute("Name", r.Key))); var xml = new XElement("CharacterRemarks", remarks); return xml.ToString(); }   static void Main(string[] args) { var characterRemarks = new Dictionary<string, string> { { "April", "Bubbly: I'm > Tam and <= Emily" }, { "Tam O'Shanter", "Burns: \"When chapman billies leave the street ...\"" }, { "Emily", "Short & shrift" } };   string xml = CreateXML(characterRemarks); Console.WriteLine(xml); } }
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
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libxml/parser.h> #include <libxml/tree.h>   static void print_names(xmlNode *node) { xmlNode *cur_node = NULL; for (cur_node = node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { if ( strcmp(cur_node->name, "Student") == 0 ) { xmlAttr *prop = NULL; if ( (prop = xmlHasProp(cur_node, "Name")) != NULL ) { printf("%s\n", prop->children->content);   } } } print_names(cur_node->children); } }   const char *buffer = "<Students>\n" " <Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n" " <Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n" " <Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n" " <Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n" " <Pet Type=\"dog\" Name=\"Rover\" />\n" " </Student>\n" " <Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n" "</Students>\n";   int main() { xmlDoc *doc = NULL; xmlNode *root = NULL;   doc = xmlReadMemory(buffer, strlen(buffer), NULL, NULL, 0); if ( doc != NULL ) { root = xmlDocGetRootElement(doc); print_names(root); xmlFreeDoc(doc); } xmlCleanupParser(); return 0; }
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)
#Slate
Slate
slate[1]> #x := ##(1 2 3). {1. 2. 3} slate[2]> x {1. 2. 3} slate[3]> #y := {1 + 2. 3 + 4. 5}. {3. 7. 5} slate[4]> y at: 2 put: 99. 99 slate[5]> y {3. 7. 99} slate[6]> x first 1 slate[7]> x at: 0. 1
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Julia
Julia
function worldcupstages() games = ["12", "13", "14", "23", "24", "34"] results = "000000"   function nextresult() if (results == "222222") return false end results = lpad(string(parse(Int, results, base=3) + 1, base=3), 6, '0') true end   points = zeros(Int, 4, 10) while true records = zeros(Int, 4) for i in 1:length(games) if results[i] == '2' records[games[i][1] - '0'] += 3 elseif results[i] == '1' records[games[i][1] - '0'] += 1 records[games[i][2] - '0'] += 1 elseif results[i] == '0' records[games[i][2] - '0'] += 3 end end sort!(records) for i in 1:4 points[i, records[i] + 1] += 1 end if !nextresult() break end end   for (i, place) in enumerate(["First", "Second", "Third", "Fourth"]) println("$place place: $(points[5 - i, :])") end end   worldcupstages()  
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Kotlin
Kotlin
// version 1.1.2   val games = arrayOf("12", "13", "14", "23", "24", "34") var results = "000000"   fun nextResult(): Boolean { if (results == "222222") return false val res = results.toInt(3) + 1 results = res.toString(3).padStart(6, '0') return true }   fun main(args: Array<String>) { val points = Array(4) { IntArray(10) } do { val records = IntArray(4) for (i in 0..5) { when (results[i]) { '2' -> records[games[i][0] - '1'] += 3 '1' -> { records[games[i][0] - '1']++ ; records[games[i][1] - '1']++ } '0' -> records[games[i][1] - '1'] += 3 } } records.sort() for (i in 0..3) points[i][records[i]]++ } while(nextResult()) println("POINTS 0 1 2 3 4 5 6 7 8 9") println("-------------------------------------------------------------") val places = arrayOf("1st", "2nd", "3rd", "4th") for (i in 0..3) { print("${places[i]} place ") points[3 - i].forEach { print("%-5d".format(it)) } println() } }
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.
#Joy
Joy
  DEFINE write-floats == ['g 0] [formatf] enconcat map rollup ['g 0] [formatf] enconcat map swap zip "filename" "w" fopen swap [[fputchars] 9 fputch] step 10 fputch] step fclose.  
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.
#jq
jq
[1, 2, 3, 1e11] as $x | $x | map(sqrt) as $y | range(0; $x|length) as $i | "\($x[$i]) \($y[$i])"
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.
#MATLAB_.2F_Octave
MATLAB / Octave
a = false(1,100); for b=1:100 for i = b:b:100 a(i) = ~a(i); end end a  
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#OpenEdge.2FProgress
OpenEdge/Progress
  DEFINE VARIABLE hxdoc AS HANDLE NO-UNDO. DEFINE VARIABLE hxroot AS HANDLE NO-UNDO. DEFINE VARIABLE hxelement AS HANDLE NO-UNDO. DEFINE VARIABLE hxtext AS HANDLE NO-UNDO. DEFINE VARIABLE lcc AS LONGCHAR NO-UNDO.   CREATE X-DOCUMENT hxdoc.   CREATE X-NODEREF hxroot. hxdoc:CREATE-NODE( hxroot, 'root', 'ELEMENT' ). hxdoc:APPEND-CHILD( hxroot ).   CREATE X-NODEREF hxelement. hxdoc:CREATE-NODE( hxelement, 'element', 'ELEMENT' ). hxroot:APPEND-CHILD( hxelement ).   CREATE X-NODEREF hxtext. hxdoc:CREATE-NODE( hxtext, 'element', 'TEXT' ). hxelement:APPEND-CHILD( hxtext ). hxtext:NODE-VALUE = 'Some text here'.   hxdoc:SAVE( 'LONGCHAR', lcc ). MESSAGE STRING( lcc ) VIEW-AS ALERT-BOX.  
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
#Batch_File
Batch File
@echo off for %%b in ( "" " /$$$$$$$ /$$$$$$ /$$$$$$$$ /$$$$$$ /$$ /$$" "| $$__ $$| $$__ $$|__ $$__/| $$__ $$| $$ | $$" "| $$ \ $$| $$ \ $$ | $$ | $$ \__/| $$ | $$" "| $$$$$$$ | $$$$$$$$ | $$ | $$ | $$$$$$$$" "| $$__ $$| $$__ $$ | $$ | $$ | $$__ $$" "| $$ \ $$| $$ | $$ | $$ | $$ $$| $$ | $$" "| $$$$$$$/| $$ | $$ | $$ | $$$$$$/| $$ | $$" "|_______/ |__/ |__/ |__/ \______/ |__/ |__/" "" ) do echo(%%~b pause
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#SPL
SPL
#.writetext("file.txt","This is the string")
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Standard_ML
Standard ML
fun writeFile (path, str) = (fn strm => TextIO.output (strm, str) before TextIO.closeOut strm) (TextIO.openOut path)
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Tcl
Tcl
proc writefile {filename data} { set fd [open $filename w] ;# truncate if exists, else create try { puts -nonewline $fd $data } finally { close $fd } }
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
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions     ------------------------ WORD WHEEL ----------------------   -- wordWheelMatches :: NSString -> [String] -> String -> String on wordWheelMatches(lexicon, wordWheelRows)   set wheelGroups to group(sort(characters of ¬ concat(wordWheelRows)))   script isWheelWord on |λ|(w) script available on |λ|(a, b) length of a ≤ length of b end |λ| end script   script used on |λ|(grp) w contains item 1 of grp end |λ| end script   all(my identity, ¬ zipWith(available, ¬ group(sort(characters of w)), ¬ filter(used, wheelGroups))) end |λ| end script   set matches to filter(isWheelWord, ¬ filteredLines(wordWheelPreFilter(wordWheelRows), lexicon))   (length of matches as text) & " matches:" & ¬ linefeed & linefeed & unlines(matches) end wordWheelMatches     -- wordWheelPreFilter :: [String] -> String on wordWheelPreFilter(wordWheelRows) set pivot to item 2 of item 2 of wordWheelRows set charSet to nub(concat(wordWheelRows))   "(2 < self.length) and (self contains '" & pivot & "') " & ¬ "and not (self matches '^.*[^" & charSet & "].*$') " end wordWheelPreFilter     --------------------------- TEST ------------------------- on run set fpWordList to scriptFolder() & "unixdict.txt" if doesFileExist(fpWordList) then   wordWheelMatches(readFile(fpWordList), ¬ {"nde", "okg", "elw"})   else display dialog "Word list not found in script folder:" & ¬ linefeed & tab & fpWordList end if end run       ----------- GENERIC :: FILTERED LINES FROM FILE ----------   -- doesFileExist :: FilePath -> IO Bool on doesFileExist(strPath) set ca to current application set oPath to (ca's NSString's stringWithString:strPath)'s ¬ stringByStandardizingPath set {bln, int} to (ca's NSFileManager's defaultManager's ¬ fileExistsAtPath:oPath isDirectory:(reference)) bln and (int ≠ 1) end doesFileExist     -- filteredLines :: String -> NString -> [a] on filteredLines(predicateString, s) -- A list of lines filtered by an NSPredicate string set ca to current application   set predicate to ca's NSPredicate's predicateWithFormat:predicateString set array to ca's NSArray's ¬ arrayWithArray:(s's componentsSeparatedByString:(linefeed))   (array's filteredArrayUsingPredicate:(predicate)) as list end filteredLines     -- readFile :: FilePath -> IO NSString on readFile(strPath) set ca to current application set e to reference set {s, e} to (ca's NSString's ¬ stringWithContentsOfFile:((ca's NSString's ¬ stringWithString:strPath)'s ¬ stringByStandardizingPath) ¬ encoding:(ca's NSUTF8StringEncoding) |error|:(e)) if missing value is e then s else (localizedDescription of e) as string end if end readFile     -- scriptFolder :: () -> IO FilePath on scriptFolder() -- The path of the folder containing this script try tell application "Finder" to ¬ POSIX path of ((container of (path to me)) as alias) on error display dialog "Script file must be saved" end try end scriptFolder     ------------------------- GENERIC ------------------------   -- Tuple (,) :: a -> b -> (a, b) on Tuple(a, b) -- Constructor for a pair of values, -- possibly of two different types. {type:"Tuple", |1|:a, |2|:b, length:2} end Tuple     -- all :: (a -> Bool) -> [a] -> Bool on all(p, xs) -- True if p holds for every value in xs tell mReturn(p) set lng to length of xs repeat with i from 1 to lng if not |λ|(item i of xs, i, xs) then return false end repeat true end tell end all     -- concat :: [[a]] -> [a] -- concat :: [String] -> String on concat(xs) set lng to length of xs if 0 < lng and string is class of (item 1 of xs) then set acc to "" else set acc to {} end if repeat with i from 1 to lng set acc to acc & item i of xs end repeat acc end concat     -- eq (==) :: Eq a => a -> a -> Bool on eq(a, b) a = b end eq     -- filter :: (a -> Bool) -> [a] -> [a] on filter(p, xs) tell mReturn(p) set lst to {} set lng to length of xs repeat with i from 1 to lng set v to item i of xs if |λ|(v, i, xs) then set end of lst to v end repeat if {text, string} contains class of xs then lst as text else lst end if end tell end filter     -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl     -- group :: Eq a => [a] -> [[a]] on group(xs) script eq on |λ|(a, b) a = b end |λ| end script   groupBy(eq, xs) end group     -- groupBy :: (a -> a -> Bool) -> [a] -> [[a]] on groupBy(f, xs) -- Typical usage: groupBy(on(eq, f), xs) set mf to mReturn(f)   script enGroup on |λ|(a, x) if length of (active of a) > 0 then set h to item 1 of active of a else set h to missing value end if   if h is not missing value and mf's |λ|(h, x) then {active:(active of a) & {x}, sofar:sofar of a} else {active:{x}, sofar:(sofar of a) & {active of a}} end if end |λ| end script   if length of xs > 0 then set dct to foldl(enGroup, {active:{item 1 of xs}, sofar:{}}, rest of xs) if length of (active of dct) > 0 then sofar of dct & {active of dct} else sofar of dct end if else {} end if end groupBy     -- identity :: a -> a on identity(x) -- The argument unchanged. x end identity     -- length :: [a] -> Int on |length|(xs) set c to class of xs if list is c or string is c then length of xs else (2 ^ 29 - 1) -- (maxInt - simple proxy for non-finite) end if end |length|     -- min :: Ord a => a -> a -> a on min(x, y) if y < x then y else x end if end min     -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) -- 2nd class handler function -- lifted into 1st class script wrapper. if script is class of f then f else script property |λ| : f end script end if end mReturn     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) -- The list obtained by applying f -- to each element of xs. tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- nub :: [a] -> [a] on nub(xs) nubBy(eq, xs) end nub     -- nubBy :: (a -> a -> Bool) -> [a] -> [a] on nubBy(f, xs) set g to mReturn(f)'s |λ|   script notEq property fEq : g on |λ|(a) script on |λ|(b) not fEq(a, b) end |λ| end script end |λ| end script   script go on |λ|(xs) if (length of xs) > 1 then set x to item 1 of xs {x} & go's |λ|(filter(notEq's |λ|(x), items 2 thru -1 of xs)) else xs end if end |λ| end script   go's |λ|(xs) end nubBy       -- sort :: Ord a => [a] -> [a] on sort(xs) ((current application's NSArray's arrayWithArray:xs)'s ¬ sortedArrayUsingSelector:"compare:") as list end sort     -- take :: Int -> [a] -> [a] -- take :: Int -> String -> String on take(n, xs) if 0 < n then items 1 thru min(n, length of xs) of xs else {} end if end take     -- unlines :: [String] -> String on unlines(xs) -- A single string formed by the intercalation -- of a list of strings with the newline character. set {dlm, my text item delimiters} to ¬ {my text item delimiters, linefeed} set s to xs as text set my text item delimiters to dlm s end unlines     -- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] on zipWith(f, xs, ys) set lng to min(|length|(xs), |length|(ys)) if 1 > lng then return {} set xs_ to take(lng, xs) -- Allow for non-finite set ys_ to take(lng, ys) -- generators like cycle etc set lst to {} tell mReturn(f) repeat with i from 1 to lng set end of lst to |λ|(item i of xs_, item i of ys_) end repeat return lst end tell end zipWith
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the dictionary. No word in a game can be repeated. The first word must be three or four letters long. Task Create a program to aid in the playing of the game by: Asking for contestants names. Choosing an initial random three or four letter word from the dictionary. Asking each contestant in their turn for a wordiff word. Checking the wordiff word is: in the dictionary, not a repetition of past words, and differs from the last appropriately. Optional stretch goals Add timing. Allow players to set a maximum playing time for the game. An internal timer accumulates how long each user takes to respond in their turns. Play is halted if the maximum playing time is exceeded on a players input. That last player must have entered a wordiff or loses. If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Perl
Perl
use strict; use warnings; use feature 'say'; use List::Util 'min';   my %cache; sub leven { my ($s, $t) = @_; return length($t) if $s eq ''; return length($s) if $t eq ''; $cache{$s}{$t} //= do { my ($s1, $t1) = (substr($s, 1), substr($t, 1)); (substr($s, 0, 1) eq substr($t, 0, 1)) ? leven($s1, $t1) : 1 + min( leven($s1, $t1), leven($s, $t1), leven($s1, $t ), ); }; }   print "What is your name?"; my $name = <STDIN>; $name = 'Number 6'; say "What is your quest? Never mind that, I will call you '$name'"; say 'Hey! I am not a number, I am a free man!';   my @starters = grep { length() < 6 } my @words = grep { /.{2,}/ } split "\n", `cat unixdict.txt`;   my(%used,@possibles,$guess); my $rounds = 0; my $word = say $starters[ rand $#starters ];   while () { say "Word in play: $word"; $used{$word} = 1; @possibles = (); for my $w (@words) { next if abs(length($word) - length($w)) > 1; push @possibles, $w if leven($word, $w) == 1 and ! defined $used{$w}; } print "Your word? "; $guess = <STDIN>; chomp $guess; last unless grep { $guess eq $_ } @possibles; $rounds++; $word = $guess; }   my $already = defined $used{$guess} ? " '$guess' was already played but" : '';   if (@possibles) { say "\nSorry $name,${already} one of <@possibles> would have continued the game." } else { say "\nGood job $name,${already} there were no possible words to play." } say "You made it through $rounds rounds.";
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.
#FreeBASIC
FreeBASIC
' version 21-06-2015 ' compile with: fbc -s console or fbc -s gui ' Xiaolin Wu’s line-drawing algorithm 'shared var and macro's   Dim Shared As UInteger wu_color   #Macro ipart(x) Int(x) ' integer part #EndMacro   #Macro round(x) Int((x) + .5) ' round off #EndMacro   #Macro fpart(x) Frac(x) ' fractional part #EndMacro   #Macro rfpart(x) ' 1 - Frac(x) ' seems to give problems for very small x IIf(1 - Frac(x) >= 1, 1, 1 - Frac(x)) #EndMacro   #Macro plot(x, y , c) ' use the alpha channel to set the amount of color PSet(x,y), wu_color Or (Int(c * 255)) Shl 24 #EndMacro   Sub drawline(x0 As Single, y0 As Single, x1 As Single, y1 As Single,_ col As UInteger = RGB(255,255,255))   wu_color = col And &HFFFFFF ' strip off the alpha channel information   Dim As Single gradient Dim As Single xend, yend, xgap, intery Dim As UInteger xpxl1, ypxl1, xpxl2, ypxl2, x Dim As Integer steep = Abs(y1 - y0) > Abs(x1 - x0) ' boolean   If steep Then Swap x0, y0 Swap x1, y1 End If   If x0 > x1 Then Swap x0, x1 Swap y0, y1 End If   gradient = (y1 - y0) / (x1 - x0)   ' first endpoint ' xend = round(x0) xend = ipart(x0) yend = y0 + gradient * (xend - x0) xgap = rfpart(x0 + .5) xpxl1 = xend ' this will be used in the main loop ypxl1 = ipart(yend) If steep Then plot(ypxl1, xpxl1, rfpart(yend) * xgap) plot(ypxl1+1, xpxl1, fpart(yend) * xgap) Else plot(xpxl1, ypxl1, rfpart(yend) * xgap) plot(xpxl1, ypxl1+1, fpart(yend) * xgap) End If intery = yend + gradient ' first y-intersecction for the main loop   ' handle second endpoint ' xend = round(x1) xend = ipart(x1) yend = y1 + gradient * (xend - x1) xgap = fpart(x1 + .5) xpxl2 = xend ' this will be used in the main loop ypxl2 = ipart(yend) If steep Then plot(ypxl2, xpxl2, rfpart(yend) * xgap) plot(ypxl2+1, xpxl2, fpart(yend) * xgap) Else plot(xpxl2, ypxl2, rfpart(yend) * xgap) plot(xpxl2, ypxl2+1, fpart(yend) * xgap) End If   ' main loop If steep Then For x = xpxl1 + 1 To xpxl2 - 1 plot(ipart(intery), x, rfpart(intery)) plot(ipart(intery)+1, x, fpart(intery)) intery = intery + gradient Next Else For x = xpxl1 + 1 To xpxl2 - 1 plot(x, ipart(intery), rfpart(intery)) plot(x, ipart(intery)+1, fpart(intery)) intery = intery + gradient Next End If   End Sub   ' ------=< MAIN >=------   #Define W_ 600 #Define H_ 600   #Include Once "fbgfx.bi" ' needed setting the screen attributes Dim As Integer i Dim As String fname = __FILE__   ScreenRes W_, H_, 32,, FB.GFX_ALPHA_PRIMITIVES   Randomize Timer   For i = 0 To H_ Step H_\30 drawline(0, 0, W_, i, Int(Rnd * &HFFFFFF)) Next   For i = 0 To W_ Step W_\30 drawline(0, 0, i, H_, Int(Rnd * &HFFFFFF)) Next   i = InStr(fname,".bas") fname = Left(fname, Len(fname)-i+1) WindowTitle fname + " hit any key to end program"   While Inkey <> "" : Wend Sleep End
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#C.2B.2B
C++
#include <vector> #include <utility> #include <iostream> #include <boost/algorithm/string.hpp>   std::string create_xml( std::vector<std::string> & ,std::vector<std::string> & ) ;   int main( ) { std::vector<std::string> names , remarks ; names.push_back( "April" ) ; names.push_back( "Tam O'Shantor" ) ; names.push_back ( "Emily" ) ; remarks.push_back( "Bubbly, I'm > Tam and <= Emily" ) ; remarks.push_back( "Burns: \"When chapman billies leave the street ...\"" ) ; remarks.push_back( "Short & shrift" ) ; std::cout << "This is in XML:\n" ; std::cout << create_xml( names , remarks ) << std::endl ; return 0 ; }   std::string create_xml( std::vector<std::string> & names , std::vector<std::string> & remarks ) { std::vector<std::pair<std::string , std::string> > entities ; entities.push_back( std::make_pair( "&" , "&amp;" ) ) ; entities.push_back( std::make_pair( "<" , "&lt;" ) ) ; entities.push_back( std::make_pair( ">" , "&gt;" ) ) ; std::string xmlstring ( "<CharacterRemarks>\n" ) ; std::vector<std::string>::iterator vsi = names.begin( ) ; typedef std::vector<std::pair<std::string , std::string> >::iterator Vpss ; for ( ; vsi != names.end( ) ; vsi++ ) { for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) { boost::replace_all ( *vsi , vs->first , vs->second ) ; } } for ( vsi = remarks.begin( ) ; vsi != remarks.end( ) ; vsi++ ) { for ( Vpss vs = entities.begin( ) ; vs != entities.end( ) ; vs++ ) { boost::replace_all ( *vsi , vs->first , vs->second ) ; } } for ( int i = 0 ; i < names.size( ) ; i++ ) { xmlstring.append( "\t<Character name=\"").append( names[ i ] ).append( "\">") .append( remarks[ i ] ).append( "</Character>\n" ) ; } xmlstring.append( "</CharacterRemarks>" ) ; return xmlstring ; }
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
#C.23
C#
  class Program { static void Main(string[] args) { XDocument xmlDoc = XDocument.Load("XMLFile1.xml"); var query = from p in xmlDoc.Descendants("Student") select p.Attribute("Name");   foreach (var item in query) { Console.WriteLine(item.Value); } Console.ReadLine(); } }  
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)
#Smalltalk
Smalltalk
#(1 2 3 'four' 5.0 true false nil (10 20) $a)
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Lua
Lua
function array1D(a, d) local m = {} for i=1,a do table.insert(m, d) end return m end   function array2D(a, b, d) local m = {} for i=1,a do table.insert(m, array1D(b, d)) end return m end   function fromBase3(num) local out = 0 for i=1,#num do local c = num:sub(i,i) local d = tonumber(c) out = 3 * out + d end return out end   function toBase3(num) local ss = "" while num > 0 do local rem = num % 3 num = math.floor(num / 3) ss = ss .. tostring(rem) end return string.reverse(ss) end   games = { "12", "13", "14", "23", "24", "34" }   results = "000000" function nextResult() if results == "222222" then return false end   local res = fromBase3(results) results = string.format("%06s", toBase3(res + 1))   return true end   points = array2D(4, 10, 0)   repeat local records = array1D(4, 0)   for i=1,#games do if results:sub(i,i) == '2' then local j = tonumber(games[i]:sub(1,1)) records[j] = records[j] + 3 elseif results:sub(i,i) == '1' then local j = tonumber(games[i]:sub(1,1)) records[j] = records[j] + 1 j = tonumber(games[i]:sub(2,2)) records[j] = records[j] + 1 elseif results:sub(i,i) == '0' then local j = tonumber(games[i]:sub(2,2)) records[j] = records[j] + 3 end end   table.sort(records) for i=1,#records do points[i][records[i]+1] = points[i][records[i]+1] + 1 end until not nextResult()   print("POINTS 0 1 2 3 4 5 6 7 8 9") print("-------------------------------------------------------------") places = { "1st", "2nd", "3rd", "4th" } for i=1,#places do io.write(places[i] .. " place") local row = points[i] for j=1,#row do io.write(string.format("%5d", points[5 - i][j])) end print() end
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Julia
Julia
xprecision = 3 yprecision = 5 x = round.([1, 2, 3, 1e11],xprecision) y = round.([1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791],yprecision) writedlm("filename", [x y], '\t')
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.
#Kotlin
Kotlin
// version 1.1.2   import java.io.File   fun main(args: Array<String>) { val x = doubleArrayOf(1.0, 2.0, 3.0, 1e11) val y = doubleArrayOf(1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791) val xp = 3 val yp = 5 val f = "%.${xp}g\t%.${yp}g\n" val writer = File("output.txt").writer() writer.use { for (i in 0 until x.size) { val s = f.format(x[i], y[i]) writer.write(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.
#Maxima
Maxima
doors(n) := block([v], local(v), v: makelist(true, n), for i: 2 thru n do for j: i step i thru n do v[j]: not v[j], sublist_indices(v, 'identity));
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Oz
Oz
declare proc {Main} DOM = root(element("Some text here")) in {System.showInfo {Serialize DOM}} end ...
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Pascal
Pascal
program CrearXML;   {$mode objfpc}{$H+}   uses Classes, XMLWrite, DOM;   var xdoc: TXMLDocument; // variable objeto documento XML NodoRaiz, NodoPadre, NodoHijo: TDOMNode; // variables a los nodos begin //crear el documento xdoc := TXMLDocument.create;   NodoRaiz := xdoc.CreateElement('root'); // crear el nodo raíz Xdoc.Appendchild(NodoRaiz); // guardar nodo raíz NodoPadre := xdoc.CreateElement('element'); // crear el nodo hijo NodoHijo := xdoc.CreateTextNode('Some text here'); // insertar el valor del nodo NodoPadre.Appendchild(NodoHijo); // guardar nodo NodoRaiz.AppendChild(NodoPadre); // insertar el nodo hijo en el correspondiente nodo padre writeXMLFile(xDoc,'prueba.xml'); // escribir el XML NodoRaiz.free; NodoPadre.free; NodoHijo.free; Xdoc.free; end.
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
#Befunge
Befunge
0" &7&%h&'&%| &7&%7%&%&'&%&'&%&7&%"v v"'%$%'%$%3$%$%7% 0%&7&%&7&(%$%'%$"< >"%$%7%$%&%$%&'&%7%$%7%$%, '&+(%$%"v v"+&'&%+('%$%$%'%$%$%$%$%$%$%$%'%$"< >"(%$%$%'%$%$%( %$+(%&%$+(%&%$+(%&"v v"(; $%$%(+$%&%(+$%$%'%$%+&%$%$%$%"< ? ";(;(+(+$%+(%&(;(3%$%&$ 7`+( ":v > ^v!:-1<\,:g7+*63%4 \/_#4:_v#:-*84_$@ $_\:,\^ >55+,$:^:$
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT content="new text that will overwrite content of myfile" LOOP path2file=FULLNAME (TUSTEP,"myfile",-std-) status=WRITE (path2file,content) IF (status=="OK") EXIT IF (status=="CREATE") ERROR/STOP CREATE ("myfile",seq-o,-std-) ENDLOOP  
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#VBA
VBA
  Option Explicit   Const strName As String = "MyFileText.txt" Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _ "The reverse of Read entire file—for when you want to update or " & vbCrLf & _ "create a file which you would read in its entirety all at once."   Sub Main() Dim Nb As Integer   Nb = FreeFile Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb Print #1, Text Close #Nb End Sub
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
#AutoHotkey
AutoHotkey
letters := ["N", "D", "E", "O", "K", "G", "E", "L", "W"]   FileRead, wList, % A_Desktop "\unixdict.txt" result := "" for word in Word_wheel(wList, letters, 3) result .= word "`n" MsgBox % result return   Word_wheel(wList, letters, minL){ oRes := [] for i, w in StrSplit(wList, "`n", "`r") { if (StrLen(w) < minL) continue word := w for i, l in letters w := StrReplace(w, l,,, 1) if InStr(word, letters[5]) && !StrLen(w) oRes[word] := true } return oRes }
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the dictionary. No word in a game can be repeated. The first word must be three or four letters long. Task Create a program to aid in the playing of the game by: Asking for contestants names. Choosing an initial random three or four letter word from the dictionary. Asking each contestant in their turn for a wordiff word. Checking the wordiff word is: in the dictionary, not a repetition of past words, and differs from the last appropriately. Optional stretch goals Add timing. Allow players to set a maximum playing time for the game. An internal timer accumulates how long each user takes to respond in their turns. Play is halted if the maximum playing time is exceeded on a players input. That last player must have entered a wordiff or loses. If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Python
Python
# -*- coding: utf-8 -*-   from typing import List, Tuple, Dict, Set from itertools import cycle, islice from collections import Counter import re import random import urllib   dict_fname = 'unixdict.txt' dict_url1 = 'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt' # ~25K words dict_url2 = 'https://raw.githubusercontent.com/dwyl/english-words/master/words.txt' # ~470K words   word_regexp = re.compile(r'^[a-z]{3,}$') # reduce dict words to those of three or more a-z characters.     def load_dictionary(fname: str=dict_fname) -> Set[str]: "Return appropriate words from a dictionary file" with open(fname) as f: return {lcase for lcase in (word.strip().lower() for word in f) if word_regexp.match(lcase)}   def load_web_dictionary(url: str) -> Set[str]: "Return appropriate words from a dictionary web page" words = urllib.request.urlopen(url).read().decode().strip().lower().split() return {word for word in words if word_regexp.match(word)}     def get_players() -> List[str]: "Return inputted ordered list of contestant names." names = input('Space separated list of contestants: ') return [n.capitalize() for n in names.strip().split()]   def is_wordiff(wordiffs: List[str], word: str, dic: Set[str], comment=True) -> bool: "Is word a valid wordiff from wordiffs[-1] ?" if word not in dic: if comment: print('That word is not in my dictionary') return False if word in wordiffs: if comment: print('That word was already used.') return False if len(word) < len(wordiffs[-1]): return is_wordiff_removal(word, wordiffs[-1], comment) elif len(word) > len(wordiffs[-1]): return is_wordiff_insertion(word, wordiffs[-1], comment)   return is_wordiff_change(word, wordiffs[-1], comment)     def is_wordiff_removal(word: str, prev: str, comment=True) -> bool: "Is word derived from prev by removing one letter?" ... ans = word in {prev[:i] + prev[i+1:] for i in range(len(prev))} if not ans: if comment: print('Word is not derived from previous by removal of one letter.') return ans     def is_wordiff_insertion(word: str, prev: str, comment=True) -> bool: "Is word derived from prev by adding one letter?" diff = Counter(word) - Counter(prev) diffcount = sum(diff.values()) if diffcount != 1: if comment: print('More than one character insertion difference.') return False   insert = list(diff.keys())[0] ans = word in {prev[:i] + insert + prev[i:] for i in range(len(prev) + 1)} if not ans: if comment: print('Word is not derived from previous by insertion of one letter.') return ans     def is_wordiff_change(word: str, prev: str, comment=True) -> bool: "Is word derived from prev by changing exactly one letter?" ... diffcount = sum(w != p for w, p in zip(word, prev)) if diffcount != 1: if comment: print('More or less than exactly one character changed.') return False return True   def could_have_got(wordiffs: List[str], dic: Set[str]): return (word for word in (dic - set(wordiffs)) if is_wordiff(wordiffs, word, dic, comment=False))   if __name__ == '__main__': dic = load_web_dictionary(dict_url2) dic_3_4 = [word for word in dic if len(word) in {3, 4}] start = random.choice(dic_3_4) wordiffs = [start] players = get_players() for name in cycle(players): word = input(f"{name}: Input a wordiff from {wordiffs[-1]!r}: ").strip() if is_wordiff(wordiffs, word, dic): wordiffs.append(word) else: print(f'YOU HAVE LOST {name}!') print("Could have used:", ', '.join(islice(could_have_got(wordiffs, dic), 10)), '...') break
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.
#Go
Go
package raster   import "math"   func ipart(x float64) float64 { return math.Floor(x) }   func round(x float64) float64 { return ipart(x + .5) }   func fpart(x float64) float64 { return x - ipart(x) }   func rfpart(x float64) float64 { return 1 - fpart(x) }   // AaLine plots anti-aliased line by Xiaolin Wu's line algorithm. func (g *Grmap) AaLine(x1, y1, x2, y2 float64) { // straight translation of WP pseudocode dx := x2 - x1 dy := y2 - y1 ax := dx if ax < 0 { ax = -ax } ay := dy if ay < 0 { ay = -ay } // plot function set here to handle the two cases of slope var plot func(int, int, float64) if ax < ay { x1, y1 = y1, x1 x2, y2 = y2, x2 dx, dy = dy, dx plot = func(x, y int, c float64) { g.SetPx(y, x, uint16(c*math.MaxUint16)) } } else { plot = func(x, y int, c float64) { g.SetPx(x, y, uint16(c*math.MaxUint16)) } } if x2 < x1 { x1, x2 = x2, x1 y1, y2 = y2, y1 } gradient := dy / dx   // handle first endpoint xend := round(x1) yend := y1 + gradient*(xend-x1) xgap := rfpart(x1 + .5) xpxl1 := int(xend) // this will be used in the main loop ypxl1 := int(ipart(yend)) plot(xpxl1, ypxl1, rfpart(yend)*xgap) plot(xpxl1, ypxl1+1, fpart(yend)*xgap) intery := yend + gradient // first y-intersection for the main loop   // handle second endpoint xend = round(x2) yend = y2 + gradient*(xend-x2) xgap = fpart(x2 + 0.5) xpxl2 := int(xend) // this will be used in the main loop ypxl2 := int(ipart(yend)) plot(xpxl2, ypxl2, rfpart(yend)*xgap) plot(xpxl2, ypxl2+1, fpart(yend)*xgap)   // main loop for x := xpxl1 + 1; x <= xpxl2-1; x++ { plot(x, int(ipart(intery)), rfpart(intery)) plot(x, int(ipart(intery))+1, fpart(intery)) intery = intery + gradient } }
http://rosettacode.org/wiki/XML/Output
XML/Output
Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks. All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element. As an example, calling the function with the three names of: April Tam O'Shanter Emily And three remarks of: Bubbly: I'm > Tam and <= Emily Burns: "When chapman billies leave the street ..." Short & shrift Should produce the XML (but not necessarily with the indentation): <CharacterRemarks> <Character name="April">Bubbly: I'm &gt; Tam and &lt;= Emily</Character> <Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character> <Character name="Emily">Short &amp; shrift</Character> </CharacterRemarks> The document may include an <?xml?> declaration and document type declaration, but these are optional. If attempting this task by direct string manipulation, the implementation must include code to perform entity substitution for the characters that have entities defined in the XML 1.0 specification. Note: the example is chosen to show correct escaping of XML strings. Note too that although the task is written to take two lists of corresponding data, a single mapping/hash/dictionary of names to remarks is also acceptable. Note to editors: Program output with escaped characters will be viewed as the character on the page so you need to 'escape-the-escapes' to make the RC entry display what would be shown in a plain text viewer (See this). Alternately, output can be placed in <lang xml></lang> tags without any special treatment.
#Clojure
Clojure
(use 'clojure.xml) (defn character-remarks-xml [characters remarks] (with-out-str (emit-element {:tag :CharacterRemarks, :attrs nil, :content (vec (for [item (map vector characters remarks)] {:tag :Character, :attrs {:name (item 0)}, :content [(item 1)]}) )})))
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
#C.2B.2B
C++
/* Using the Qt library's XML parser. */ #include <iostream>   #include <QDomDocument> #include <QObject>   int main() { QDomDocument doc;   doc.setContent( QObject::tr( "<Students>\n" "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n" "<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n" "<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n" "<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n" "<Pet Type=\"dog\" Name=\"Rover\" />\n" "</Student>\n" "<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"&#x00C9;mily\" />\n" "</Students>"));   QDomElement n = doc.documentElement().firstChildElement("Student"); while(!n.isNull()) { std::cout << qPrintable(n.attribute("Name")) << std::endl; n = n.nextSiblingElement(); } return 0; }
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)
#SNOBOL4
SNOBOL4
ar = ARRAY("3,2")  ;* 3 rows, 2 columns fill i = LT(i, 3) i + 1  :F(display) ar<i,1> = i ar<i,2> = i "-count"  :(fill)   display  ;* fail on end of array j = j + 1 OUTPUT = "Row " ar<j,1> ": " ar<j,2> +  :S(display) END
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Nim
Nim
import algorithm, sequtils, strutils import itertools   const Scoring = [0, 1, 3]   var histo: array[4, array[10, int]]   for results in product([0, 1, 2], repeat = 6): var s: array[4, int] for (r, g) in zip(results, toSeq(combinations([0, 1, 2, 3], 2))): s[g[0]] += Scoring[r] s[g[1]] += Scoring[2 - r] for i, v in sorted(s): inc histo[i][v]   for x in reversed(histo): echo x.mapIt(($it).align(3)).join(" ")
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Perl
Perl
use Math::Cartesian::Product;   @scoring = (0, 1, 3); push @histo, [(0) x 10] for 1..4; push @aoa, [(0,1,2)] for 1..6;   for $results (cartesian {@_} @aoa) { my @s; my @g = ([0,1],[0,2],[0,3],[1,2],[1,3],[2,3]); for (0..$#g) { $r = $results->[$_]; $s[$g[$_][0]] += $scoring[$r]; $s[$g[$_][1]] += $scoring[2 - $r]; }   my @ss = sort @s; $histo[$_][$ss[$_]]++ for 0..$#s; }   $fmt = ('%3d ') x 10 . "\n"; printf $fmt, @$_ for reverse @histo;
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.
#Lingo
Lingo
on saveFloatLists (filename, x, y, xprecision, yprecision) eol = numtochar(10) -- LF fp = xtra("fileIO").new() fp.openFile(tFile, 2) cnt = x.count repeat with i = 1 to cnt the floatPrecision = xprecision fp.writeString(string(x[i]) fp.writeString(TAB) the floatPrecision = yprecision fp.writeString(string(y[i]) fp.writeString(eol) end repeat fp.closeFile() end
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; /* sqrt(x) */ xprecision = 3; yprecision = 5; The file should look like: 1 1 2 1.4142 3 1.7321 1e+011 3.1623e+005 This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
#Lua
Lua
filename = "file.txt"   x = { 1, 2, 3, 1e11 } y = { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 }; xprecision = 3; yprecision = 5;   fstr = "%."..tostring(xprecision).."f ".."%."..tostring(yprecision).."f\n"   fp = io.open( filename, "w+" )   for i = 1, #x do fp:write( string.format( fstr, x[i], y[i] ) ) end   io.close( fp )
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.
#MAXScript
MAXScript
doorsOpen = for i in 1 to 100 collect false   for pass in 1 to 100 do ( for door in pass to 100 by pass do ( doorsOpen[door] = not doorsOpen[door] ) )   for i in 1 to doorsOpen.count do ( format ("Door % is open?: %\n") i doorsOpen[i] )
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Perl
Perl
use XML::Simple; print XMLout( { root => { element => "Some text here" } }, NoAttr => 1, RootName => "" );
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Phix
Phix
with javascript_semantics include builtins/xml.e sequence elem = xml_new_element("element", "Some text here"), root = xml_new_element("root", {elem}), doc = xml_new_doc(root,{`<?xml version="1.0" ?>`}) puts(1,xml_sprint(doc))
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
#Brainf.2A.2A.2A
Brainf***
++++[>++++>++<[>>++>+++>++++++> ++++++<<<<<-]<-]>>++>..>->----> -...[<]<+++[>++++[>>...<<-]<-]> >>..>>>.....<<<..>>>...[<]++[>> .....>>>...<<<<<-]>.>.>.>.<<..> >.[<]<+++++[>++++[>>.<<-]<-]>>> ..>>>...[<]+++++[>>..<<-]+++>>. >.<..>>>...<.[[>]<.<.<<..>>.>.. <<<.<<-]+++>.>.>>.<<.>>.<<..>>. >....<<<.>>>...<<<..>>>...<<<.> >>......<<.>.>..<.<<..>>>..<<<. .>>>....<.<<..>>.>..<<.[[>]<<.> ..<<<...>>>.<.<<<<-]+++>.>..>>. <<.>>.<<...>>>..<<<.>>..<<..>>. <.<.>>>..<..>...<<<...>>.<<.>>> .<<.>>.<<.<..>>.<.<.>>>.<<<..>> .>.<<<...>>>..<.>.<<.>.>..<.<.. >>.<<.>.>..<.<..>>.<<.>.>..<.<. <<.>...>>.<<.>>.<<..>>.<.>.<<.> >..<<...>.>>..<<..>>...<.<<...> >..<<..>>..<<...>.<.>>.<<..>>.. <<..>>.>.<<.<[[>]<<<<.>>.<.>>.. <<.<..<<-]>.>....>>.<<.>>.<<..> >.>.<.<<.>>..<<..>>.<<...>.>.<< ..>>>.<<<....>>..<<..>>..<<..>> ..<<.>>.<<..>>..<<..>>.<<<.>... ..>>.<<.>>.>......<..>..<.<<..> >.<<.>>.>...<<.>.>..<..>..<..>. .<..<<.>>.>..<..>..<.<<<.>..... .>>.<.>>......<<..>>..<<.<...>> .<.>>..<<.>.<.>>..<<..>>..<<..> >..<<.<.>>.<.>>..<<..>>..<<.<<.
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#VBScript
VBScript
  Set objFSO = CreateObject("Scripting.FileSystemObject")   SourceFile = objFSO.GetParentFolderName(WScript.ScriptFullName) & "\out.txt" Content = "(Over)write a file so that it contains a string." & vbCrLf &_ "The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once."   With objFSO.OpenTextFile(SourceFile,2,True,0) .Write Content .Close End With   Set objFSO = Nothing  
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() My.Computer.FileSystem.WriteAllText("new.txt", "This is a string", False) End Sub   End Module  
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Wren
Wren
import "io" for File   // create a text file File.create("hello.txt") { |file| file.writeBytes("hello") }   // check it worked System.print(File.read("hello.txt"))   // overwrite it by 'creating' the file again File.create("hello.txt") {|file| file.writeBytes("goodbye") }   // check it worked System.print(File.read("hello.txt"))
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#11l
11l
F isOneAway(word1, word2) V result = 0B L(i) 0 .< word1.len I word1[i] != word2[i] I result R 0B E result = 1B R result   DefaultDict[Int, [String]] words   L(word) File(‘unixdict.txt’).read().split("\n") words[word.len] [+]= word   F find_path(start, target) V lg = start.len assert(target.len == lg, ‘Source and destination must have same length.’) assert(start C :words[lg], ‘Source must exist in the dictionary.’) assert(target C :words[lg], ‘Destination must exist in the dictionary.’)   V currPaths = [[start]] V pool = copy(:words[lg])   L [[String]] newPaths [String] added L(candidate) pool L(path) currPaths I isOneAway(candidate, path.last) V newPath = path [+] [candidate] I candidate == target R newPath E newPaths.append(newPath) added.append(candidate) L.break   I newPaths.empty L.break currPaths = move(newPaths) L(w) added pool.remove(w)   R [String]()   L(start, target) [(‘boy’, ‘man’), (‘girl’, ‘lady’), (‘john’, ‘jane’), (‘child’, ‘adult’), (‘cat’, ‘dog’), (‘lead’, ‘gold’), (‘white’, ‘black’), (‘bubble’, ‘tickle’)] V path = find_path(start, target) I path.empty print(‘No path from "’start‘" to "’target‘".’) E print(path.join(‘ -> ’))
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
#AWK
AWK
  # syntax: GAWK -f WORD_WHEEL.AWK letters unixdict.txt # the required letter must be first # # example: GAWK -f WORD_WHEEL.AWK Kndeogelw unixdict.txt # BEGIN { letters = tolower(ARGV[1]) required = substr(letters,1,1) size = 3 ARGV[1] = "" } { word = tolower($0) leng_word = length(word) if (word ~ required && leng_word >= size) { hits = 0 for (i=1; i<=leng_word; i++) { if (letters ~ substr(word,i,1)) { hits++ } } if (leng_word == hits && hits >= size) { for (i=1; i<=leng_word; i++) { c = substr(word,i,1) if (gsub(c,"&",word) > gsub(c,"&",letters)) { next } } words++ printf("%s ",word) } } } END { printf("\nletters: %s, '%s' required, %d words >= %d characters\n",letters,required,words,size) exit(0) }  
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the dictionary. No word in a game can be repeated. The first word must be three or four letters long. Task Create a program to aid in the playing of the game by: Asking for contestants names. Choosing an initial random three or four letter word from the dictionary. Asking each contestant in their turn for a wordiff word. Checking the wordiff word is: in the dictionary, not a repetition of past words, and differs from the last appropriately. Optional stretch goals Add timing. Allow players to set a maximum playing time for the game. An internal timer accumulates how long each user takes to respond in their turns. Play is halted if the maximum playing time is exceeded on a players input. That last player must have entered a wordiff or loses. If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#Raku
Raku
my @words = 'unixdict.txt'.IO.slurp.lc.words.grep(*.chars > 2);   my @small = @words.grep(*.chars < 6);   use Text::Levenshtein;   my ($rounds, $word, $guess, @used, @possibles) = 0;   loop { my $lev; $word = @small.pick; hyper for @words -> $this { next if ($word.chars - $this.chars).abs > 1; last if ($lev = distance($word, $this)[0]) == 1; } last if $lev; }   my $name = ',';   #[[### Entirely unnecessary and unuseful "chatty repartee" but is required by the task   run 'clear'; $name = prompt "Hello player one, what is your name? "; say "Cool. I'm going to call you Gomer."; $name = ' Gomer,'; sleep 1; say "\nPlayer two, what is your name?\nOh wait, this isn't a \"specified number of players\" game..."; sleep 1; say "Nevermind.\n";   ################################################################################]]   loop { say "Word in play: $word"; push @used, $word; @possibles = @words.hyper.map: -> $this { next if ($word.chars - $this.chars).abs > 1; $this if distance($word, $this)[0] == 1 and $this ∉ @used; } $guess = prompt "your word? "; last unless $guess ∈ @possibles; ++$rounds; say qww<Ok! Woot! 'Way to go!' Nice! 👍 😀>.pick ~ "\n"; $word = $guess; }   my $already = ($guess ∈ @used) ?? " $guess was already played but" !! '';   if @possibles { say "\nOops. Sorry{$name}{$already} one of [{@possibles}] would have continued the game." } else { say "\nGood job{$name}{$already} there were no possible words to play." } say "You made it through $rounds rounds.";
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.
#Haskell
Haskell
{-# LANGUAGE ScopedTypeVariables #-}   module Main (main) where   import Codec.Picture (writePng) import Codec.Picture.Types (Image, MutableImage(..), Pixel, PixelRGB8(..), createMutableImage, unsafeFreezeImage, writePixel) import Control.Monad (void) import Control.Monad.Primitive (PrimMonad, PrimState) import Data.Foldable (foldlM)   type MImage m px = MutableImage (PrimState m) px   -- | Create an image given a function to apply to an empty mutable image withMutableImage :: (Pixel px, PrimMonad m) => Int -- ^ image width -> Int -- ^ image height -> px -- ^ background colour -> (MImage m px -> m ()) -- ^ function to apply to mutable image -> m (Image px) -- ^ action withMutableImage w h px f = createMutableImage w h px >>= \m -> f m >> unsafeFreezeImage m   -- | Plot a pixel at the given point in the given colour plot :: (Pixel px, PrimMonad m) => MImage m px -- ^ mutable image -> Int -- ^ x-coordinate of point -> Int -- ^ y-coordinate of point -> px -- ^ colour -> m () -- ^ action plot = writePixel   -- | Draw an antialiased line from first point to second point in given colour drawAntialiasedLine :: forall px m . (Pixel px, PrimMonad m) => MImage m px -- ^ mutable image -> Int -- ^ x-coordinate of first point -> Int -- ^ y-coordinate of first point -> Int -- ^ x-coordinate of second point -> Int -- ^ y-coordinate of second point -> (Double -> px) -- ^ colour generator function -> m () -- ^ action drawAntialiasedLine m p1x p1y p2x p2y colour = do let steep = abs (p2y - p1y) > abs (p2x - p1x) ((p3x, p4x), (p3y, p4y)) = swapIf steep ((p1x, p2x), (p1y, p2y)) ((ax, ay), (bx, by)) = swapIf (p3x > p4x) ((p3x, p3y), (p4x, p4y)) dx = bx - ax dy = by - ay gradient = if dx == 0 then 1.0 else fromIntegral dy / fromIntegral dx   -- handle first endpoint let xpxl1 = ax -- round (fromIntegral ax) yend1 = fromIntegral ay + gradient * fromIntegral (xpxl1 - ax) xgap1 = rfpart (fromIntegral ax + 0.5) endpoint steep xpxl1 yend1 xgap1   -- handle second endpoint let xpxl2 = bx -- round (fromIntegral bx) yend2 = fromIntegral by + gradient * fromIntegral (xpxl2 - bx) xgap2 = fpart (fromIntegral bx + 0.5) endpoint steep xpxl2 yend2 xgap2   -- main loop let intery = yend1 + gradient void $ if steep then foldlM (\i x -> do plot m (ipart i) x (colour (rfpart i)) plot m (ipart i + 1) x (colour (fpart i)) pure $ i + gradient) intery [xpxl1 + 1..xpxl2 - 1] else foldlM (\i x -> do plot m x (ipart i) (colour (rfpart i)) plot m x (ipart i + 1) (colour (fpart i)) pure $ i + gradient) intery [xpxl1 + 1..xpxl2 - 1]   where endpoint :: Bool -> Int -> Double -> Double -> m () endpoint True xpxl yend xgap = do plot m ypxl xpxl (colour (rfpart yend * xgap)) plot m (ypxl + 1) xpxl (colour (fpart yend * xgap)) where ypxl = ipart yend endpoint False xpxl yend xgap = do plot m xpxl ypxl (colour (rfpart yend * xgap)) plot m xpxl (ypxl + 1) (colour (fpart yend * xgap)) where ypxl = ipart yend   swapIf :: Bool -> (a, a) -> (a, a) swapIf False p = p swapIf True (x, y) = (y, x)   ipart :: Double -> Int ipart = truncate   fpart :: Double -> Double fpart x | x > 0 = x - temp | otherwise = x - (temp + 1) where temp = fromIntegral (ipart x)   rfpart :: Double -> Double rfpart x = 1 - fpart x   main :: IO () main = do -- We start and end the line with sufficient clearance from the edge of the -- image to be able to see the endpoints img <- withMutableImage 640 480 (PixelRGB8 0 0 0) $ \m@(MutableImage w h _) -> drawAntialiasedLine m 2 2 (w - 2) (h - 2) (\brightness -> let level = round (brightness * 255) in PixelRGB8 level level level)   -- Write it out to a file on disc writePng "xiaolin-wu-algorithm.png" img
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.
#Common_Lisp
Common Lisp
(defun write-xml (characters lines &optional (out *standard-output*)) (let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil)) (chars (dom:append-child doc (dom:create-element doc "Characters")))) (map nil (lambda (character line) (let ((c (dom:create-element doc "Character"))) (dom:set-attribute c "name" character) (dom:append-child c (dom:create-text-node doc line)) (dom:append-child chars c))) characters lines) (write-string (dom:map-document (cxml:make-rod-sink) doc) out)))
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
#Cach.C3.A9_ObjectScript
Caché ObjectScript
Class XML.Students [ Abstract ] {   XData XMLData { <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> }   ClassMethod Output() As %Status { // get xml stream from the 'XData' block contained in this class and parse Set xdata=##class(%Dictionary.CompiledXData).%OpenId($this_"||XMLData",, .sc) If $$$ISERR(sc) Quit sc Set sc=##class(%XML.TextReader).ParseStream(xdata.Data, .hdlr) If $$$ISERR(sc) Quit sc   // iterate through document, node by node While hdlr.Read() { If hdlr.Path="/Students/Student", hdlr.MoveToAttributeName("Name") { Write hdlr.Value, ! } }   // finished Quit $$$OK }   }
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)
#SPL
SPL
a[1] = 2.5 a[2] = 3 a[3] = "Result is " #.output(a[3],a[1]+a[2])
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Phix
Phix
function game_combinations(sequence res, integer pool, needed, sequence chosen={}) if needed=0 then res = append(res,chosen) -- collect the full sets else for i=iff(length(chosen)=0?1:chosen[$]+1) to pool do res = game_combinations(res,pool,needed-1,append(deep_copy(chosen),i)) end for end if return res end function constant games = game_combinations({},4,2) -- ie {{1,2},{1,3},{1,4},{2,3},{2,4},{3,4}} constant scores = {{3,0},{1,1},{0,3}} -- ie win/draw/lose sequence points = repeat(repeat(0,10),4) -- 1st..4th place, 0..9 points procedure result_combinations(integer pool, needed, sequence chosen={}) if needed=0 then -- (here, chosen is {1,1,1,1,1,1}..{3,3,3,3,3,3}, 729 in all) sequence results = repeat(0,4) for i=1 to length(chosen) do integer {team1,team2} = games[i] integer {points1,points2} = scores[chosen[i]] results[team1] += points1 results[team2] += points2 end for results = sort(results) for i=1 to 4 do points[i][results[i]+1] += 1 end for else for i=1 to pool do result_combinations(pool,needed-1,append(deep_copy(chosen),i)) end for end if end procedure -- accumulate the results of all possible outcomes (1..3) of 6 games: result_combinations(3,6) -- (the result ends up in points) --result_combinations(length(scores),length(games)) -- (equivalent) constant fmt = join(repeat("%5d",10))&"\n", cardinals = {"st","nd","rd","th"} printf(1," points "&fmt&repeat('-',69)&"\n",tagset(9,0)) for i=1 to 4 do printf(1,"%d%s place "&fmt,{i,cardinals[i]}&points[5-i]) end for
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
exportPrec[path_, data1_, data2_, prec1_, prec2_] := Export[ path, Transpose[{Map[ToString[NumberForm[#, prec2]] &, data2], Map[ToString[NumberForm[#, prec1]] &, data1]}], "Table" ]
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.
#MATLAB_.2F_Octave
MATLAB / Octave
x = [1, 2, 3, 1e11]; y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791];   fid = fopen('filename','w') fprintf(fid,'%.3g\t%.5g\n',[x;y]); fclose(fid);
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.
#Mercury
Mercury
:- module doors. :- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module bitmap, bool, list, string, int.   :- func doors = bitmap. doors = bitmap.init(100, no).   :- pred walk(int, bitmap, bitmap). :- mode walk(in, bitmap_di, bitmap_uo) is det. walk(Pass, !Doors) :- walk(Pass, Pass, !Doors).   :- pred walk(int, int, bitmap, bitmap). :- mode walk(in, in, bitmap_di, bitmap_uo) is det. walk(At, By, !Doors) :- ( if bitmap.in_range(!.Doors, At - 1) then bitmap.unsafe_flip(At - 1, !Doors), walk(At + By, By, !Doors) else true ).   :- pred report(bitmap, int, io, io). :- mode report(bitmap_di, in, di, uo) is det. report(Doors, N, !IO) :- ( if is_set(Doors, N - 1) then State = "open" else State = "closed" ), io.format("door #%d is %s\n", [i(N), s(State)], !IO).   main(!IO) :- list.foldl(walk, 1 .. 100, doors, Doors), list.foldl(report(Doors), 1 .. 100, !IO).
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#PHP
PHP
<?php $dom = new DOMDocument();//the constructor also takes the version and char-encoding as it's two respective parameters $dom->formatOutput = true;//format the outputted xml $root = $dom->createElement('root'); $element = $dom->createElement('element'); $element->appendChild($dom->createTextNode('Some text here')); $root->appendChild($element); $dom->appendChild($root); $xmlstring = $dom->saveXML();
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#PicoLisp
PicoLisp
(load "@lib/xm.l")   (xml? T) (xml '(root NIL (element NIL "Some text here")))
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
#C
C
#include <stdio.h> const char*s = " _____\n /____/\\\n/ ___\\/\n\\ \\/__/\n \\____/"; int main(){ puts(s); return 0; }
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#XLISP
XLISP
(define n (open-output-file "example.txt")) (write "(Over)write a file so that it contains a string." n) (close-output-port n)
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#XPL0
XPL0
[FSet(FOpen("output.txt", 1), ^o); Text(3, "This is a string."); ]
http://rosettacode.org/wiki/Write_entire_file
Write entire file
Task (Over)write a file so that it contains a string. The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
#Xtend
Xtend
  package com.rosetta.example   import java.io.File import java.io.PrintStream   class WriteFile { def static main( String ... args ) { val fout = new PrintStream(new File(args.get(0))) fout.println("Some text.") fout.close } }  
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
#11l
11l
F word_wrap(text, line_width) V words = text.split_py() I words.empty R ‘’ V wrapped = words[0] V space_left = line_width - wrapped.len L(word) words[1..] I word.len + 1 > space_left wrapped ‘’= "\n"word space_left = line_width - word.len E wrapped ‘’= ‘ ’word space_left -= 1 + word.len R wrapped   V frog = ‘ In olden times when wishing still helped one, there lived a king whose daughters were all beautiful, but the youngest was so beautiful that the sun itself, which has seen so much, was astonished whenever it shone in her face. Close by the king's castle lay a great dark forest, and under an old lime-tree in the forest was a well, and when the day was very warm, the king's child went out into the forest and sat down by the side of the cool fountain, and when she was bored she took a golden ball, and threw it up on high and caught it, and this ball was her favorite plaything.’   L(width) (72, 80) print(‘Wrapped at ’width":\n"word_wrap(frog, width)) print()
http://rosettacode.org/wiki/Word_ladder
Word ladder
Yet another shortest path problem. Given two words of equal length the task is to transpose the first into the second. Only one letter may be changed at a time and the change must result in a word in unixdict, the minimum number of intermediate words should be used. Demonstrate the following: A boy can be made into a man: boy -> bay -> ban -> man With a little more difficulty a girl can be made into a lady: girl -> gill -> gall -> gale -> gaze -> laze -> lazy -> lady A john can be made into a jane: john -> cohn -> conn -> cone -> cane -> jane A child can not be turned into an adult. Optional transpositions of your choice. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#ALGOL_68
ALGOL 68
# quick implementation of a stack of INT. real program starts after it. # MODE STACK = STRUCT (INT top, FLEX[1:0]INT data, INT increment);   PROC makestack = (INT increment)STACK: (1, (), increment);   PROC pop = (REF STACK s)INT: ( top OF s -:= 1; (data OF s)[top OF s] );   PROC push = (REF STACK s, INT n)VOID: BEGIN IF top OF s > UPB data OF s THEN [ UPB data OF s + increment OF s ]INT tmp; tmp[1 : UPB data OF s] := data OF s; data OF s := tmp FI; (data OF s)[top OF s] := n; top OF s +:= 1 END;   PROC empty = (REF STACK s)BOOL: top OF s <= 1;   PROC contents = (REF STACK s)[]INT: (data OF s)[:top OF s - 1];   # start solution #   []STRING words = BEGIN # load dictionary file into array # FILE f; BOOL eof := FALSE; open(f, "unixdict.txt", stand in channel); on logical file end(f, (REF FILE f)BOOL: eof := TRUE); INT idx := 1; FLEX [1:0] STRING words; STRING word; WHILE NOT eof DO get(f, (word, newline)); IF idx > UPB words THEN HEAP [1 : UPB words + 10000]STRING tmp; tmp[1 : UPB words] := words; words := tmp FI; words[idx] := word; idx +:= 1 OD; words[1:idx-1] END;   INT nwords = UPB words;   INT max word length = (INT mwl := 0; FOR i TO UPB words DO IF mwl < UPB words[i] THEN mwl := UPB words[i] FI OD; mwl);   [nwords]FLEX[0]INT neighbors;   [max word length]BOOL precalculated by length;   FOR i TO UPB precalculated by length DO precalculated by length[i] := FALSE OD;   # precalculating neighbours takes time, but not doing it is even slower... # PROC precalculate neighbors = (INT word length)VOID: BEGIN [nwords]REF STACK stacks; FOR i TO UPB stacks DO stacks[i] := NIL OD; FOR i TO UPB words DO IF UPB words[i] = word length THEN IF REF STACK(stacks[i]) :=: NIL THEN stacks[i] := HEAP STACK := makestack(10) FI; FOR j FROM i + 1 TO UPB words DO IF UPB words[j] = word length THEN IF neighboring(words[i], words[j]) THEN push(stacks[i], j); IF REF STACK(stacks[j]) :=: NIL THEN stacks[j] := HEAP STACK := makestack(10) FI; push(stacks[j], i) FI FI OD FI OD; FOR i TO UPB neighbors DO IF REF STACK(stacks[i]) :/=: NIL THEN neighbors[i] := contents(stacks[i]) FI OD; precalculated by length [word length] := TRUE END;   PROC neighboring = (STRING a, b)BOOL: # do a & b differ in just 1 char? # BEGIN INT diff := 0; FOR i TO UPB a DO IF a[i] /= b[i] THEN diff +:= 1 FI OD; diff = 1 END;   PROC word ladder = (STRING from, STRING to)[]STRING: BEGIN IF UPB from /= UPB to THEN fail FI; INT word length = UPB from; IF word length < 1 OR word length > max word length THEN fail FI; IF from = to THEN fail FI; INT start := 0; INT destination := 0; FOR i TO UPB words DO IF UPB words[i] = word length THEN IF words[i] = from THEN start := i ELIF words[i] = to THEN destination := i FI FI OD; IF destination = 0 OR start = 0 THEN fail FI; IF NOT precalculated by length [word length] THEN precalculate neighbors(word length) FI; STACK stack := makestack(1000); [nwords]INT distance; [nwords]INT previous; FOR i TO nwords DO distance[i] := nwords+1; previous[i] := 0 OD; INT shortest := nwords+1; distance[start] := 0; push(stack, start); WHILE NOT empty(stack) DO INT curr := pop(stack); INT dist := distance[curr]; IF dist < shortest - 1 THEN # find neighbors and add them to the stack # FOR i FROM UPB neighbors[curr] BY -1 TO 1 DO INT n = neighbors[curr][i]; IF distance[n] > dist + 1 THEN distance[n] := dist + 1; previous[n] := curr; IF n = destination THEN shortest := dist + 1 ELSE push(stack, n) FI FI OD; IF curr = destination THEN shortest := dist FI FI OD; INT length = distance[destination] + 1; IF length > nwords THEN fail FI; [length]STRING result; INT curr := destination; FOR i FROM length BY -1 TO 1 DO result[i] := words[curr]; curr := previous[curr] OD; result EXIT fail: LOC [0] STRING END;   [][]STRING pairs = (("boy", "man"), ("bed", "cot"), ("old", "new"), ("dry", "wet"),   ("girl", "lady"), ("john", "jane"), ("lead", "gold"), ("poor", "rich"), ("lamb", "stew"), ("kick", "goal"), ("cold", "warm"), ("nude", "clad"),   ("child", "adult"), ("white", "black"), ("bread", "toast"), ("lager", "stout"), ("bride", "groom"), ("table", "chair"),   ("bubble", "tickle"));   FOR i TO UPB pairs DO STRING from = pairs[i][1], to = pairs[i][2]; []STRING ladder = word ladder(from, to); IF UPB ladder = 0 THEN print(("No solution for """ + from + """ -> """ + to + """", newline)) ELSE FOR j TO UPB ladder DO print(((j > 1 | "->" | ""), ladder[j])) OD; print(newline) FI OD
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
#BASIC
BASIC
10 DEFINT A-Z 20 DATA "ndeokgelw","unixdict.txt" 30 READ WH$, F$ 40 OPEN "I",1,F$ 50 IF EOF(1) THEN CLOSE 1: END 60 C$ = WH$ 70 LINE INPUT #1, W$ 80 FOR I=1 TO LEN(W$) 90 FOR J=1 TO LEN(C$) 100 IF MID$(W$,I,1)=MID$(C$,J,1) THEN MID$(C$,J,1)="@": GOTO 120 110 NEXT J: GOTO 50 120 NEXT I 130 IF MID$(C$,(LEN(C$)+1)/2,1)<>"@" GOTO 50 140 C=0: FOR I=1 TO LEN(C$): C=C-(MID$(C$,I,1)="@"): NEXT 150 IF C>=3 THEN PRINT W$, 160 GOTO 50
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
#BCPL
BCPL
get "libhdr"   // Read word from selected input let readword(v) = valof $( let ch = ? v%0 := 0 $( ch := rdch() if ch = endstreamch then resultis false if ch = '*N' then resultis true v%0 := v%0 + 1 v%(v%0) := ch $) repeat $)   // Test word against wheel let match(wheel, word) = valof $( let wcopy = vec 2+9/BYTESPERWORD for i = 0 to wheel%0 do wcopy%i := wheel%i for i = 1 to word%0 do $( let idx = ? test valof $( for j = 1 to wcopy%0 do if word%i = wcopy%j then $( idx := j resultis true $) resultis false $) then wcopy%idx := 0 // we've used this letter else resultis false // word cannot be made $) resultis wcopy%((wcopy%0+1)/2)=0 & // middle letter must be used 3 <= valof // at least 3 letters must be used $( let count = 0 for i = 1 to wcopy%0 do if wcopy%i=0 then count := count + 1 resultis count $) $)   // Test unixdict.txt against ndeokgelw let start() be $( let word = vec 2+64/BYTESPERWORD let file = findinput("unixdict.txt") let wheel = "ndeokgelw"   selectinput(file) while readword(word) do if match(wheel, word) do writef("%S*N", word) endread() $)
http://rosettacode.org/wiki/Wordiff
Wordiff
Wordiff is an original game in which contestants take turns spelling new dictionary words of three or more characters that only differ from the last by a change in one letter. The change can be either: a deletion of one letter; addition of one letter; or change in one letter. Note: All words must be in the dictionary. No word in a game can be repeated. The first word must be three or four letters long. Task Create a program to aid in the playing of the game by: Asking for contestants names. Choosing an initial random three or four letter word from the dictionary. Asking each contestant in their turn for a wordiff word. Checking the wordiff word is: in the dictionary, not a repetition of past words, and differs from the last appropriately. Optional stretch goals Add timing. Allow players to set a maximum playing time for the game. An internal timer accumulates how long each user takes to respond in their turns. Play is halted if the maximum playing time is exceeded on a players input. That last player must have entered a wordiff or loses. If the game is timed-out, the loser is the person who took the longest `average` time to answer in their rounds. Other tasks related to string operations: Metrics Array length String length Copy a string Empty string  (assignment) Counting Word frequency Letter frequency Jewels and stones I before E except after C Bioinformatics/base count Count occurrences of a substring Count how many vowels and consonants occur in a string Remove/replace XXXX redacted Conjugate a Latin verb Remove vowels from a string String interpolation (included) Strip block comments Strip comments from a string Strip a set of characters from a string Strip whitespace from a string -- top and tail Strip control codes and extended characters from a string Anagrams/Derangements/shuffling Word wheel ABC problem Sattolo cycle Knuth shuffle Ordered words Superpermutation minimisation Textonyms (using a phone text pad) Anagrams Anagrams/Deranged anagrams Permutations/Derangements Find/Search/Determine ABC words Odd words Word ladder Semordnilap Word search Wordiff  (game) String matching Tea cup rim text Alternade words Changeable words State name puzzle String comparison Unique characters Unique characters in each string Extract file extension Levenshtein distance Palindrome detection Common list elements Longest common suffix Longest common prefix Compare a list of strings Longest common substring Find common directory path Words from neighbour ones Change e letters to i in words Non-continuous subsequences Longest common subsequence Longest palindromic substrings Longest increasing subsequence Words containing "the" substring Sum of the digits of n is substring of n Determine if a string is numeric Determine if a string is collapsible Determine if a string is squeezable Determine if a string has all unique characters Determine if a string has all the same characters Longest substrings without repeating characters Find words which contains all the vowels Find words which contains most consonants Find words which contains more than 3 vowels Find words which first and last three letters are equals Find words which odd letters are consonants and even letters are vowels or vice_versa Formatting Substring Rep-string Word wrap String case Align columns Literals/String Repeat a string Brace expansion Brace expansion using ranges Reverse a string Phrase reversals Comma quibbling Special characters String concatenation Substring/Top and tail Commatizing numbers Reverse words in a string Suffixation of decimal numbers Long literals, with continuations Numerical and alphabetical suffixes Abbreviations, easy Abbreviations, simple Abbreviations, automatic Song lyrics/poems/Mad Libs/phrases Mad Libs Magic 8-ball 99 Bottles of Beer The Name Game (a song) The Old lady swallowed a fly The Twelve Days of Christmas Tokenize Text between Tokenize a string Word break problem Tokenize a string with escaping Split a character string based on change of character Sequences Show ASCII table De Bruijn sequences Self-referential sequences Generate lower case ASCII alphabet
#REXX
REXX
/*REXX program acts as a host and allows two or more people to play the WORDIFF game.*/ signal on halt /*allow the user(s) to halt the game. */ parse arg iFID seed . /*obtain optional arguments from the CL*/ if iFID=='' | iFID=="," then iFID='unixdict.txt' /*Not specified? Then use the default.*/ if datatype(seed, 'W') then call random ,,seed /*If " " " " seed. */ call read call IDs first= random(1, min(100000, starters) ) /*get a random start word for the game.*/ list= $$$.first say; say eye "OK, let's play the WORDIFF game."; say; say do round=1 do player=1 for players call show; ou= o; upper ou call CBLF word(names, player) end /*players*/ end /*round*/   halt: say; say; say eye 'The WORDIFF game has been halted.' done: exit 0 /*stick a fork in it, we're all done. */ quit: say; say; say eye 'The WORDDIF game is quitting.'; signal done /*──────────────────────────────────────────────────────────────────────────────────────*/ isMix: return datatype(arg(1), 'M') /*return unity if arg has mixed letters*/ ser: say; say eye '***error*** ' arg(1).; say; return /*issue error message. */ last: parse arg y; return word(y, words(y) ) /*get last word in list.*/ over: call ser 'word ' _ x _ arg(1); say eye 'game over,' you; signal done /*game over*/ show: o= last(list); say; call what; say; L= length(o); return verE: m= 0; do v=1 for L; m= m + (substr(ou,v,1)==substr(xu,v,1)); end; return m==L-1 verL: do v=1 for L; if space(overlay(' ', ou, v), 0)==xu then return 1; end; return 0 verG: do v=1 for w; if space(overlay(' ', xu, v), 0)==ou then return 1; end; return 0 what: say eye 'The current word in play is: ' _ o _; return /*──────────────────────────────────────────────────────────────────────────────────────*/ CBLF: parse arg you /*ask carbon-based life form for a word*/ do getword=0 by 0 until x\=='' say eye "What's your word to be played, " you'?' parse pull x; x= space(x); #= words(x); if #==0 then iterate; w= length(x) if #>1 then do; call ser 'too many words given: ' x x=; iterate getword end if \isMix(x) then do; call ser 'the name' _ x _ " isn't alphabetic" x=; iterate getword end end /*getword*/   if wordpos(x, list)>0 then call over " has already been used" xu= x; upper xu /*obtain an uppercase version of word. */ if \@.xu then call over " doesn't exist in the dictionary: " iFID if length(x) <3 then call over " must be at least three letters long." if w <L then if \verL() then call over " isn't a legal letter deletion." if w==L then if \verE() then call over " isn't a legal letter substitution." if w >L then if \verG() then call over " isn't a legal letter addition." list= list x /*add word to the list of words used. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ IDs:  ?= "Enter the names of the people that'll be playing the WORDIFF game (or Quit):" names= /*start with a clean slate (of names). */ do getIDs=0 by 0 until words(names)>1 say; say eye ? parse pull ids; ids= space( translate(ids, , ',') ) /*elide any commas. */ if ids=='' then iterate; q= ids; upper q /*use uppercase QUIT*/ if abbrev('QUIT', q, 1) then signal quit do j=1 for words(ids); x= word(ids, j) if \isMix(x) then do; call ser 'the name' _ x _ " isn't alphabetic" names=; iterate getIDs end if wordpos(x, names)>0 then do; call ser 'the name' _ x _ " is already taken" names=; iterate getIDs end names= space(names x) end /*j*/ end /*getIDs*/ say players= words(names) do until ans\=='' say eye 'The ' players " player's names are: " names say eye 'Is this correct?'; pull ans; ans= space(ans) end /*until*/ yeahs= 'yah yeah yes ja oui si da'; upper yeahs do ya=1 for words(yeahs) if abbrev( word(yeahs, ya), ans, 2) | ans=='Y' then return end /*ya*/ call IDS; return /*──────────────────────────────────────────────────────────────────────────────────────*/ read: _= '───'; eye= copies('─', 8) /*define a couple of eye catchers. */ say; say eye eye eye 'Welcome to the WORDIFF word game.' eye eye eye; say @.= 0; starters= 0 do r=1 while lines(iFID)\==0 /*read each word in the file (word=X).*/ x= strip(linein(iFID)) /*pick off a word from the input line. */ if \isMix(x) then iterate /*Not a suitable word for WORDIFF? Skip*/ y= x; upper x /*pick off a word from the input line. */ @.x= 1; L= length(x) /*set a semaphore for uppercased word. */ if L<3 | L>4 then iterate /*only use short words for the start. */ starters= starters + 1 /*bump the count of starter words. */ $$$.starters= y /*save short words for the starter word*/ end /*#*/ if r>100 & starters> 10 then return /*is the dictionary satisfactory ? */ call ser 'Dictionary file ' _ iFID _ "wasn't found or isn't satisfactory."; exit 13
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.
#J
J
load'gl2' coinsert'jgl2'   drawpt=:4 :0"0 1 glrgb <.(-.x)*255 255 255 glpixel y )   drawLine=:3 :0 NB. drawline x1,y1,x2,y2 pts=. 2 2$y isreversed=. </ |d=. -~/pts r=. |.^:isreversed"1 pts=. /:~ pts \:"1 |d gradient=. %~/ (\:|)d   'x y'=. |:pts xend=. <.0.5+ x yend=. y + gradient* xend-x xgap=. -.1|x+0.5   n=. i. >: -~/ xend 'xlist ylist'=. (n*/~1,gradient) + ({.xend),({.yend) weights=. ((2&}.,~ xgap*2&{.)&.(_1&|.) (,.~-.) 1|ylist) weights (drawpt r)"1 2 (,:+&0 1)"1 xlist,.<.ylist )
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.
#D
D
import kxml.xml; char[][][]characters = [["April","Bubbly: I'm > Tam and <= Emily"], ["Tam O'Shanter","Burns: \"When chapman billies leave the street ...\""], ["Emily","Short & shrift"]]; void addChars(XmlNode root,char[][][]info) { auto remarks = new XmlNode("CharacterRemarks"); root.addChild(remarks); foreach(set;info) { remarks.addChild((new XmlNode("Character")).setAttribute("name",set[0]).addCData(set[1])); } } void main() { auto root = new XmlNode(""); root.addChild(new XmlPI("xml")); addChars(root,characters); std.stdio.writefln("%s",root.write); }
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
#Clojure
Clojure
  (import '(java.io ByteArrayInputStream)) (use 'clojure.xml) ; defines 'parse   (def xml-text "<Students> <Student Name='April' Gender='F' DateOfBirth='1989-01-02' /> <Student Name='Bob' Gender='M' DateOfBirth='1990-03-04' /> <Student Name='Chad' Gender='M' DateOfBirth='1991-05-06' /> <Student Name='Dave' Gender='M' DateOfBirth='1992-07-08'> <Pet Type='dog' Name='Rover' /> </Student> <Student DateOfBirth='1993-09-10' Gender='F' Name='&#x00C9;mily' /> </Students>")   (def students (parse (-> xml-text .getBytes ByteArrayInputStream.)))  
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)
#SSEM
SSEM
load register 0, #0  ; running total load register 1, #0  ; index loop: add register 0, array+register 1 add register 1, #1 compare register 1, #4 branchIfLess loop
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Python
Python
from itertools import product, combinations, izip   scoring = [0, 1, 3] histo = [[0] * 10 for _ in xrange(4)]   for results in product(range(3), repeat=6): s = [0] * 4 for r, g in izip(results, combinations(range(4), 2)): s[g[0]] += scoring[r] s[g[1]] += scoring[2 - r]   for h, v in izip(histo, sorted(s)): h[v] += 1   for x in reversed(histo): print x
http://rosettacode.org/wiki/World_Cup_group_stage
World Cup group stage
It's World Cup season (or at least it was when this page was created)! The World Cup is an international football/soccer tournament that happens every 4 years.   Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games.   Once a team has qualified they are put into a group with 3 other teams. For the first part of the World Cup tournament the teams play in "group stage" games where each of the four teams in a group plays all three other teams once.   The results of these games determine which teams will move on to the "knockout stage" which is a standard single-elimination tournament.   The two teams from each group with the most standings points move on to the knockout stage. Each game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team.   A win is worth three points.   A draw/tie is worth one point.   A loss is worth zero points. Task   Generate all possible outcome combinations for the six group stage games.   With three possible outcomes for each game there should be 36 = 729 of them.   Calculate the standings points for each team with each combination of outcomes.   Show a histogram (graphical,   ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes. Don't worry about tiebreakers as they can get complicated.   We are basically looking to answer the question "if a team gets x standings points, where can they expect to end up in the group standings?". Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three.   Oddly enough, there is no way to get 8 points at all.
#Racket
Racket
#lang racket ;; Tim Brown 2014-09-15 (define (sort-standing stndg#) (sort (hash->list stndg#) > #:key cdr))   (define (hash-update^2 hsh key key2 updater2 dflt2) (hash-update hsh key (λ (hsh2) (hash-update hsh2 key2 updater2 dflt2)) hash))   (define all-standings (let ((G '((a b) (a c) (a d) (b c) (b d) (c d))) (R '((3 0) (1 1) (0 3)))) (map sort-standing (for*/list ((r1 R) (r2 R) (r3 R) (r4 R) (r5 R) (r6 R)) (foldr (λ (gm rslt h) (hash-update (hash-update h (second gm) (λ (n) (+ n (second rslt))) 0) (first gm) (curry + (first rslt)) 0)) (hash) G (list r1 r2 r3 r4 r5 r6))))))   (define histogram (for*/fold ((rv (hash))) ((stndng (in-list all-standings)) (psn (in-range 0 4))) (hash-update^2 rv (add1 psn) (cdr (list-ref stndng psn)) add1 0)))   ;; Generalised histogram printing functions... (define (show-histogram hstgrm# captions) (define (min* a b) (if (and a b) (min a b) (or a b))) (define-values (position-mn position-mx points-mn points-mx) (for*/fold ((mn-psn #f) (mx-psn 0) (mn-pts #f) (mx-pts 0)) (((psn rw) (in-hash hstgrm#))) (define-values (min-pts max-pts) (for*/fold ((mn mn-pts) (mx mx-pts)) ((pts (in-hash-keys rw))) (values (min* pts mn) (max pts mx)))) (values (min* mn-psn psn) (max mx-psn psn) min-pts max-pts)))   (define H (let ((lbls-row# (for/hash ((i (in-range points-mn (add1 points-mx)))) (values i i)))) (hash-set hstgrm# 'thead lbls-row#)))   (define cap-col-width (for/fold ((m 0)) ((v (in-hash-values captions))) (max m (string-length v))))   (for ((plc (in-sequences (in-value 'thead) (in-range position-mn (add1 position-mx))))) (define cnts (for/list ((pts (in-range points-mn (add1 points-mx)))) (~a #:align 'center #:width 3 (hash-ref (hash-ref H plc) pts 0)))) (printf "~a ~a~%" (~a (hash-ref captions plc (curry format "#~a:")) #:width cap-col-width) (string-join cnts " "))))   (define captions (hash 'thead "POINTS:" 1 "1st Place:" 2 "2nd Place:" 3 "Sack the manager:" 4 "Sack the team!"))   (show-histogram histogram captions)
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.
#Mercury
Mercury
:- module write_float_arrays. :- interface.   :- import_module io.   :- pred main(io::di, io::uo) is det. :- implementation.   :- import_module float, list, math, string.   main(!IO) :- io.open_output("filename", OpenFileResult, !IO), ( OpenFileResult = ok(File), X = [1.0, 2.0, 3.0, 1e11], list.foldl_corresponding(write_dat(File, 3, 5), X, map(sqrt, X), !IO), io.close_output(File, !IO)  ; OpenFileResult = error(IO_Error), io.stderr_stream(Stderr, !IO), io.format(Stderr, "error: %s\n", [s(io.error_message(IO_Error))], !IO), io.set_exit_status(1, !IO) ).   :- pred write_dat(text_output_stream::in, int::in, int::in, float::in, float::in, io::di, io::uo) is det.   write_dat(File, XPrec, YPrec, X, Y, !IO) :- io.format(File, "%.*g\t%.*g\n", [i(XPrec), f(X), i(YPrec), f(Y)], !IO).
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.
#NetRexx
NetRexx
/* NetRexx */   options replace format comments java crossref savelog symbols nobinary   -- Invent a target text file name based on this program's source file name parse source . . pgmName '.nrx' . outFile = pgmName || '.txt'   do formatArrays(outFile, [1, 2, 3, 1e+11], [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]) catch ex = Exception ex.printStackTrace end   return   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- This function formats the input arrays. -- It has defaults for the x & y precision values of 3 & 5 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method formatArrays(outFile, xf = Rexx[], yf = Rexx[], xprecision = 3, yprecision = 5) - public static signals IllegalArgumentException, FileNotFoundException, IOException   if xf.length > yf.length then signal IllegalArgumentException('Y array must be at least as long as X array')   fw = BufferedWriter(OutputStreamWriter(FileOutputStream(outFile)))   loop i_ = 0 to xf.length - 1 row = xf[i_].format(null, xprecision, null, xprecision).left(15) yf[i_].format(null, yprecision, null, yprecision) (Writer fw).write(String row) fw.newLine end i_ fw.close   return  
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.
#Metafont
Metafont
boolean doors[]; for i = 1 upto 100: doors[i] := false; endfor for i = 1 upto 100: for j = 1 step i until 100: doors[j] := not doors[j]; endfor endfor for i = 1 upto 100: message decimal(i) & " " & if doors[i]: "open" else: "close" fi; endfor end
http://rosettacode.org/wiki/XML/DOM_serialization
XML/DOM serialization
Create a simple DOM and having it serialize to: <?xml version="1.0" ?> <root> <element> Some text here </element> </root>
#Pike
Pike
object dom = Parser.XML.Tree.SimpleRootNode(); dom->add_child(Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_HEADER, "", ([]), "")); object node = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "root", ([]), ""); dom->add_child(node);   object subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_ELEMENT, "element", ([]), ""); node->add_child(subnode);   node = subnode; subnode = Parser.XML.Tree.SimpleNode(Parser.XML.Tree.XML_TEXT, "", ([]), "Some text here"); node->add_child(subnode);   dom->render_xml(); Result: "<?xml version='1.0' encoding='utf-8'?><root><element>Some text here</element></root>"