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 po...
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 w...
#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 ...
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...
#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) ...
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...
#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 Dictionar...
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) { ...
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 ...
#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"...
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" /...
#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,...
#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; ...
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 internat...
#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 internat...
#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 f...
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
Write float arrays to a text file
Task Write two equal-sized numerical arrays 'x' and 'y' to a two-column text file named 'filename'. The first column of the file contains values from an 'x'-array with a given 'xprecision', the second -- values from 'y'-array with 'yprecision'. For example, considering: x = {1, 2, 3, 1e11}; y = {1, 1.41421356...
#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.41421356...
#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...
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...
#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()->Pri...
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...
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 w...
#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 arg...
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 w...
#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...
#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...
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 translati...
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 ...
#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 xm...
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" /...
#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->n...
http://rosettacode.org/wiki/Arrays
Arrays
This task is about arrays. For hashes or associative arrays, please see Creating an Associative Array. For a definition and in-depth discussion of what an array is, see Array. Task Show basic array syntax in your language. Basically, create an array, assign a value to it, and retrieve an element   (if available,...
#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 internat...
#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(In...
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 internat...
#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 =...
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.41421356...
#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.41421356...
#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...
#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...
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 ( "" " /$$$$$$$ /$$$$$$ /$$$$$$$$ /$$$$$$ /$$ /$$" "| $$__ $$| $$__ $$|__ $$__/| $$__ $$| $$ | $$" "| $$ \ $$| $$ \ $$ | $$ | $$ \__/| $$ | $$" "| $$$$$$$ | $$$$$$$$ | $$ | $$ | $$$$$$$$" "| $$__ $$| $$__ $$ | $$ | $$ | $$__ $$" "| $$ \ $$| $$ | $$ | $$ ...
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 w...
#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...
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...
#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))...
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) ...
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 ...
#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" ) ; nam...
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" /...
#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);...
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,...
#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 internat...
#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...
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.41421356...
#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.41421356...
#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()...
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...
#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 ...
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_$@ $_\:,\^ ...
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."   ...
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 w...
#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 (S...
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...
#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.githubuse...
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...
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 ...
#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, ...
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" /...
#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=\"Bo...
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,...
#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 internat...
#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] fo...
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 internat...
#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...
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.41421356...
#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.wri...
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.41421356...
#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...
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...
#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 en...
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....
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 ...
#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) ...
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 w...
#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) ...
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...
#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; ...
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.Fo...
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 ...
#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"...
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" /...
#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...
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,...
#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 internat...
#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)) ...
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.41421356...
#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.41421356...
#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...
#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) :- ...
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')); ...
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, sho...
#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...
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 ...
#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: BE...
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 w...
#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)<...
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 w...
#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, wo...
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...
#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...
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 ...
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 ...
#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"); ...
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" /...
#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' Ge...
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,...
#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 internat...
#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(his...
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 internat...
#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))) ...
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.41421356...
#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], ...
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.41421356...
#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, 316...
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...
#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, "...