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/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.
| #xTalk | xTalk |
on mouseUp
repeat with tStep = 1 to 100
repeat with tDoor = tStep to 100 step tStep
put not tDoors[tDoor] into tDoors[tDoor]
end repeat
if tDoors[tStep] then put "Door " & tStep & " is open" & cr after tList
end repeat
set the text of field "Doors" to tList
end mouseUp
|
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>
| #Forth | Forth | include ffl/dom.fs
\ Create a dom variable 'doc' in the dictionary
dom-create doc
\ Add the document root with its version attribute
dom.document doc dom-append-node
s" version" s" 1.0" dom.attribute doc dom-append-node
\ Add root and element
doc dom-parent 2drop
s" root" dom.element doc dom-append-node
s" element" dom.element doc dom-append-node
\ Add the text
s" Some text here" dom.text doc dom-append-node
\ Convert the document to a string and print
doc dom-write-string [IF]
type cr
[THEN] |
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>
| #Go | Go | package main
import (
"fmt"
dom "gitlab.com/stone.code/xmldom-go.git"
)
func main() {
d, err := dom.ParseStringXml(`
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>`)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(d.ToXml()))
} |
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.
| #Lua | Lua | function writeFile (filename, data)
local f = io.open(filename, 'w')
f:write(data)
f:close()
end
writeFile("stringFile.txt", "Mmm... stringy.") |
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.
| #Maple | Maple | Export("directory/filename.txt", 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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Export["filename.txt","contents string"] |
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 > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & 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.
| #Action.21 | Action! | DEFINE PTR="CARD"
DEFINE CHARACTER_SIZE="4"
TYPE Character=[PTR name,remark]
PTR FUNC GetCharacterPointer(BYTE ARRAY d INT index)
RETURN (d+index*CHARACTER_SIZE)
PROC SetCharacter(BYTE ARRAY d INT index CHAR ARRAY n,r)
Character POINTER ch
ch=GetCharacterPointer(d,index)
ch.name=n
ch.remark=r
RETURN
PROC PrintEscaped(CHAR ARRAY s)
INT i
CHAR c
FOR i=1 TO s(0)
DO
c=s(i)
IF c='< THEN
Print("<")
ELSEIF c='> THEN
Print(">")
ELSEIF c='& THEN
Print("&")
ELSE
Put(c)
FI
OD
RETURN
PROC OutputNode(CHAR ARRAY node,tagName,tagValue BYTE closing)
Put('<)
IF closing THEN Put('/) FI
Print(node)
IF tagName(0)>0 THEN
PrintF(" %S=""",tagName)
PrintEscaped(tagValue) Put('")
FI
Put('>)
RETURN
PROC OutputCharacter(Character POINTER ch)
CHAR ARRAY node="Character"
OutputNode(node,"name",ch.name,0)
PrintEscaped(ch.remark)
OutputNode(node,"","",1)
RETURN
PROC OutputCharacters(BYTE ARRAY d INT count)
CHAR ARRAY node="CharacterRemarks"
Character POINTER ch
INT i
OutputNode(node,"","",0) PutE()
FOR i=0 TO count-1
DO
ch=GetCharacterPointer(d,i)
OutputCharacter(ch) PutE()
OD
OutputNode(node,"","",1) PutE()
RETURN
PROC Main()
BYTE count=[3]
BYTE ARRAY d(12)
SetCharacter(d,0,"April","Bubbly: I'm > Tam and <= Emily")
SetCharacter(d,1,"Tam O'Shanter","Burns: ""When chapman billies leave the street ...""")
SetCharacter(d,2,"Emily","Short & shrift")
OutputCharacters(d,count)
RETURN |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Ada | Ada | with Sax.Readers;
with Input_Sources.Strings;
with Unicode.CES.Utf8;
with My_Reader;
procedure Extract_Students is
Sample_String : String :=
"<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=""Émily"" />" &
"</Students>";
Reader : My_Reader.Reader;
Input : Input_Sources.Strings.String_Input;
begin
Input_Sources.Strings.Open (Sample_String, Unicode.CES.Utf8.Utf8_Encoding, Input);
My_Reader.Parse (Reader, Input);
Input_Sources.Strings.Close (Input);
end Extract_Students; |
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)
| #Scala | Scala | // Create a new integer array with capacity 10
val a = new Array[Int](10)
// Create a new array containing specified items
val b = Array("foo", "bar", "baz")
// Assign a value to element zero
a(0) = 42
// Retrieve item at element 2
val c = b(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.
| #C.2B.2B | C++ | #include <algorithm>
#include <array>
#include <iomanip>
#include <iostream>
#include <sstream>
std::array<std::string, 6> games{ "12", "13", "14", "23", "24", "34" };
std::string results = "000000";
int fromBase3(std::string num) {
int out = 0;
for (auto c : num) {
int d = c - '0';
out = 3 * out + d;
}
return out;
}
std::string toBase3(int num) {
std::stringstream ss;
while (num > 0) {
int rem = num % 3;
num /= 3;
ss << rem;
}
auto str = ss.str();
std::reverse(str.begin(), str.end());
return str;
}
bool nextResult() {
if (results == "222222") {
return false;
}
auto res = fromBase3(results);
std::stringstream ss;
ss << std::setw(6) << std::setfill('0') << toBase3(res + 1);
results = ss.str();
return true;
}
int main() {
std::array<std::array<int, 10>, 4> points;
for (auto &row : points) {
std::fill(row.begin(), row.end(), 0);
}
do {
std::array<int, 4> records {0, 0, 0, 0 };
for (size_t i = 0; i < games.size(); i++) {
switch (results[i]) {
case '2':
records[games[i][0] - '1'] += 3;
break;
case '1':
records[games[i][0] - '1']++;
records[games[i][1] - '1']++;
break;
case '0':
records[games[i][1] - '1'] += 3;
break;
default:
break;
}
}
std::sort(records.begin(), records.end());
for (size_t i = 0; i < records.size(); i++) {
points[i][records[i]]++;
}
} while (nextResult());
std::cout << "POINTS 0 1 2 3 4 5 6 7 8 9\n";
std::cout << "-------------------------------------------------------------\n";
std::array<std::string, 4> places{ "1st", "2nd", "3rd", "4th" };
for (size_t i = 0; i < places.size(); i++) {
std::cout << places[i] << " place";
for (size_t j = 0; j < points[i].size(); j++) {
std::cout << std::setw(5) << points[3 - i][j];
}
std::cout << '\n';
}
return 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.
| #Euphoria | Euphoria | constant x = {1, 2, 3, 1e11},
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}
integer fn
fn = open("filename","w")
for n = 1 to length(x) do
printf(fn,"%.3g\t%.5g\n",{x[n],y[n]})
end for
close(fn) |
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.
| #Logo | Logo | to doors
;Problem 100 Doors
;FMSLogo
;lrcvs 2010
make "door (vector 100 1)
for [p 1 100][setitem :p :door 0]
for [a 1 100 1][for [b :a 100 :a][make "x item :b :door
ifelse :x = 0 [setitem :b :door 1][setitem :b :door 0] ] ]
for [c 1 100][make "y item :c :door
ifelse :y = 0 [pr (list :c "Close)] [pr (list :c "Open)] ]
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>
| #Groovy | Groovy | import groovy.xml.MarkupBuilder
def writer = new StringWriter() << '<?xml version="1.0" ?>\n'
def xml = new MarkupBuilder(writer)
xml.root() {
element('Some text here' )
}
println writer |
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>
| #Haskell | Haskell | import Data.List
import Text.XML.Light
xmlDOM :: String -> String
xmlDOM txt = showTopElement $ Element
(unqual "root")
[]
[ Elem $ Element
(unqual "element")
[]
[Text $ CData CDataText txt Nothing]
Nothing
]
Nothing |
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
| #11l | 11l | V s =
|‘ XX
X
X
X
X
X
XXXXX’
V lines = s.split("\n")
V width = max(lines.map(l -> l.len))
L(line) lines
print((‘ ’ * (lines.len - L.index - 1))‘’(line.ljust(width).replace(‘ ’, ‘ ’).replace(‘X’, ‘__/’) * 3)) |
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.
| #Nanoquery | Nanoquery | import Nanoquery.IO
new(File, fname).create().write(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.
| #Nim | Nim |
writeFile("filename.txt", "An arbitrary 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.
| #Objeck | Objeck | use System.IO.File;
class WriteFile {
function : Main(args : String[]) ~ Nil {
writer ← FileWriter→New("test.txt");
leaving {
writer→Close();
};
writer→WriteString("this is a test string");
}
} |
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.
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
REAL one
PROC PutBigPixel(INT x,y,col)
IF x>=0 AND x<=79 AND y>=0 AND y<=47 THEN
y==LSH 2
IF col<0 THEN col=0
ELSEIF col>15 THEN col=15 FI
Color=col
Plot(x,y)
DrawTo(x,y+3)
FI
RETURN
INT FUNC Abs(INT x)
IF x<0 THEN RETURN (-x) FI
RETURN (x)
PROC Swap(INT POINTER a,b)
INT tmp
tmp=a^ a^=b^ b^=tmp
RETURN
PROC Line(INT x1,y1,x2,y2,col)
INT x,y,dx,dy,c
INT POINTER px,py
REAL rx,ry,grad,rcol,tmp1,tmp2
dx=Abs(x2-x1)
dy=Abs(y2-y1)
IF dy>dx THEN
Swap(@x1,@y1)
Swap(@x2,@y2)
px=@y py=@x
ELSE
px=@x py=@y
FI
IF x1>x2 THEN
Swap(@x1,@x2)
Swap(@y1,@y2)
FI
x=x2-x1
IF x=0 THEN x=1 FI
IntToRealForNeg(x,rx)
IntToRealForNeg(y2-y1,ry)
RealDiv(ry,rx,grad)
IntToRealForNeg(y1,ry)
IntToReal(col,rcol)
FOR x=x1 TO x2
DO
Frac(ry,tmp1)
IF IsNegative(tmp1) THEN
RealAdd(one,tmp1,tmp2)
RealAssign(tmp2,tmp1)
FI
RealMult(rcol,tmp1,tmp2)
c=Round(tmp2)
y=Floor(ry)
PutBigPixel(px^,py^,col-c)
y==+1
PutBigPixel(px^,py^,c)
RealAdd(ry,grad,tmp1)
RealAssign(tmp1,ry)
OD
RETURN
PROC Main()
BYTE CH=$02FC ;Internal hardware value for last key pressed
REAL tmp,c
BYTE i,x1,y1,x2,y2
MathInit()
IntToReal(1,one)
Graphics(9)
FOR i=0 TO 11
DO
Line(0,i*4,38,1+i*5,15)
Line(40+i*4,0,41+i*6,47,15)
OD
DO UNTIL CH#$FF OD
CH=$FF
RETURN |
http://rosettacode.org/wiki/XML/Output | XML/Output | Create a function that takes a list of character names and a list of corresponding remarks and returns an XML document of <Character> elements each with a name attributes and each enclosing its remarks.
All <Character> elements are to be enclosed in turn, in an outer <CharacterRemarks> element.
As an example, calling the function with the three names of:
April
Tam O'Shanter
Emily
And three remarks of:
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
Should produce the XML (but not necessarily with the indentation):
<CharacterRemarks>
<Character name="April">Bubbly: I'm > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & 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.
| #Ada | Ada | with Ada.Strings.Unbounded;
with Ada.Text_IO.Text_Streams;
with DOM.Core.Documents;
with DOM.Core.Elements;
with DOM.Core.Nodes;
procedure Character_Remarks is
package DC renames DOM.Core;
package IO renames Ada.Text_IO;
package US renames Ada.Strings.Unbounded;
type Remarks is record
Name : US.Unbounded_String;
Text : US.Unbounded_String;
end record;
type Remark_List is array (Positive range <>) of Remarks;
My_Remarks : Remark_List :=
((US.To_Unbounded_String ("April"),
US.To_Unbounded_String ("Bubbly: I'm > Tam and <= Emily")),
(US.To_Unbounded_String ("Tam O'Shanter"),
US.To_Unbounded_String ("Burns: ""When chapman billies leave the street ...""")),
(US.To_Unbounded_String ("Emily"),
US.To_Unbounded_String ("Short & shrift")));
My_Implementation : DC.DOM_Implementation;
My_Document : DC.Document := DC.Create_Document (My_Implementation);
My_Root_Node : DC.Element := DC.Nodes.Append_Child (My_Document,
DC.Documents.Create_Element (My_Document, "CharacterRemarks"));
My_Element_Node : DC.Element;
My_Text_Node : DC.Text;
begin
for I in My_Remarks'Range loop
My_Element_Node := DC.Nodes.Append_Child (My_Root_Node,
DC.Documents.Create_Element (My_Document, "Character"));
DC.Elements.Set_Attribute (My_Element_Node, "Name", US.To_String (My_Remarks (I).Name));
My_Text_Node := DC.Nodes.Append_Child (My_Element_Node,
DC.Documents.Create_Text_Node (My_Document, US.To_String (My_Remarks (I).Text)));
end loop;
DC.Nodes.Write (IO.Text_Streams.Stream (IO.Standard_Output),
N => My_Document,
Pretty_Print => True);
end Character_Remarks; |
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="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Aikido | Aikido |
import xml
var s = openin ("t.xml")
var tree = XML.parseStream (s)
foreach node tree {
if (node.name == "Students") {
foreach studentnode node {
if (studentnode.name == "Student") {
println (studentnode.getAttribute ("Name"))
}
}
}
}
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Scheme | Scheme | (let ((array #(1 2 3 4 5)) ; vector literal
(array2 (make-vector 5)) ; default is unspecified
(array3 (make-vector 5 0))) ; default 0
(vector-set! array 0 3)
(vector-ref array 0)) ; 3 |
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.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static System.Console;
using static System.Linq.Enumerable;
namespace WorldCupGroupStage
{
public static class WorldCupGroupStage
{
static int[][] _histogram;
static WorldCupGroupStage()
{
int[] scoring = new[] { 0, 1, 3 };
_histogram = Repeat<Func<int[]>>(()=>new int[10], 4).Select(f=>f()).ToArray();
var teamCombos = Range(0, 4).Combinations(2).Select(t2=>t2.ToArray()).ToList();
foreach (var results in Range(0, 3).CartesianProduct(6))
{
var points = new int[4];
foreach (var (result, teams) in results.Zip(teamCombos, (r, t) => (r, t)))
{
points[teams[0]] += scoring[result];
points[teams[1]] += scoring[2 - result];
}
foreach(var (p,i) in points.OrderByDescending(a => a).Select((p,i)=>(p,i)))
_histogram[i][p]++;
}
}
// https://gist.github.com/martinfreedman/139dd0ec7df4737651482241e48b062f
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> seqs) =>
seqs.Aggregate(Empty<T>().ToSingleton(), (acc, sq) => acc.SelectMany(a => sq.Select(s => a.Append(s))));
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<T> seq, int repeat = 1) =>
Repeat(seq, repeat).CartesianProduct();
static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq) =>
seq.Aggregate(Empty<T>().ToSingleton(), (a, b) => a.Concat(a.Select(x => x.Append(b))));
static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq, int numItems) =>
seq.Combinations().Where(s => s.Count() == numItems);
private static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; }
static new string ToString()
{
var sb = new StringBuilder();
var range = String.Concat(Range(0, 10).Select(i => $"{i,-3} "));
sb.AppendLine($"Points : {range}");
var u = String.Concat(Repeat("─", 40+13));
sb.AppendLine($"{u}");
var places = new[] { "First", "Second", "Third", "Fourth" };
foreach (var row in _histogram.Select((r, i) => (r, i)))
{
sb.Append($"{places[row.i],-6} place: ");
foreach (var standing in row.r)
sb.Append($"{standing,-3} ");
sb.Append("\n");
}
return sb.ToString();
}
static void Main(string[] args)
{
Write(ToString());
Read();
}
}
}
|
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #F.23 | F# | [<EntryPoint>]
let main argv =
let x = [ 1.; 2.; 3.; 1e11 ]
let y = List.map System.Math.Sqrt x
let xprecision = 3
let yprecision = 5
use file = System.IO.File.CreateText("float.dat")
let line = sprintf "%.*g\t%.*g"
List.iter2 (fun x y -> file.WriteLine (line xprecision x yprecision y)) x y
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.
| #Forth | Forth | create x 1e f, 2e f, 3e f, 1e11 f,
create y 1e f, 2e fsqrt f, 3e fsqrt f, 1e11 fsqrt f,
: main
s" sqrt.txt" w/o open-file throw to outfile-id
4 0 do
4 set-precision
x i floats + f@ f.
6 set-precision
y i floats + f@ f. cr
loop
outfile-id stdout to outfile-id
close-file throw ; |
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.
| #LOLCODE | LOLCODE | HAI 1.3
I HAS A doors ITZ A BUKKIT
IM IN YR hallway UPPIN YR door TIL BOTH SAEM door AN 100
doors HAS A SRS door ITZ FAIL BTW, INISHULIZE ALL TEH DOORZ AS CLOZD
IM OUTTA YR hallway
IM IN YR hallway UPPIN YR pass TIL BOTH SAEM pass AN 100
I HAS A door ITZ pass
IM IN YR passer
doors'Z SRS door R NOT doors'Z SRS door
door R SUM OF door AN SUM OF pass AN 1
DIFFRINT door AN SMALLR OF door AN 99, O RLY?
YA RLY, GTFO
OIC
IM OUTTA YR passer
IM OUTTA YR hallway
IM IN YR printer UPPIN YR door TIL BOTH SAEM door AN 100
VISIBLE "Door #" SUM OF door AN 1 " is "!
doors'Z SRS door, O RLY?
YA RLY, VISIBLE "open."
NO WAI, VISIBLE "closed."
OIC
IM OUTTA YR printer
KTHXBYE |
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>
| #J | J | serialize=: ('<?xml version="1.0" ?>',LF),;@serialize1&''
serialize1=:4 :0
if.L.x do.
start=. y,'<',(0{::x),'>',LF
middle=. ;;(}.x) serialize1&.> <' ',y
end=. y,'</',(0{::x),'>',LF
<start,middle,end
else.
<y,x,LF
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>
| #Java | Java |
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class RDOMSerialization {
private Document domDoc;
public RDOMSerialization() {
return;
}
protected void buildDOMDocument() {
DocumentBuilderFactory factory;
DocumentBuilder builder;
DOMImplementation impl;
Element elmt1;
Element elmt2;
try {
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
impl = builder.getDOMImplementation();
domDoc = impl.createDocument(null, null, null);
elmt1 = domDoc.createElement("root");
elmt2 = domDoc.createElement("element");
elmt2.setTextContent("Some text here");
domDoc.appendChild(elmt1);
elmt1.appendChild(elmt2);
}
catch (ParserConfigurationException ex) {
ex.printStackTrace();
}
return;
}
protected void serializeXML() {
DOMSource domSrc;
Transformer txformer;
StringWriter sw;
StreamResult sr;
try {
domSrc = new DOMSource(domDoc);
txformer = TransformerFactory.newInstance().newTransformer();
txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
txformer.setOutputProperty(OutputKeys.METHOD, "xml");
txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
txformer.setOutputProperty(OutputKeys.INDENT, "yes");
txformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
sw = new StringWriter();
sr = new StreamResult(sw);
txformer.transform(domSrc, sr);
System.out.println(sw.toString());
}
catch (TransformerConfigurationException ex) {
ex.printStackTrace();
}
catch (TransformerFactoryConfigurationError ex) {
ex.printStackTrace();
}
catch (TransformerException ex) {
ex.printStackTrace();
}
return;
}
public static void serializationDriver(String[] args) {
RDOMSerialization lcl = new RDOMSerialization();
lcl.buildDOMDocument();
lcl.serializeXML();
return;
}
public static void main(String[] args) {
serializationDriver(args);
return;
}
}
|
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
| #360_Assembly | 360 Assembly | THREED CSECT
STM 14,12,12(13)
BALR 12,0
USING *,12
XPRNT =CL23'0 ####. #. ###.',23
XPRNT =CL24'1 #. #. #. #.',24
XPRNT =CL24'1 ##. # ##. #. #.',24
XPRNT =CL24'1 #. #. #. #. #.',24
XPRNT =CL23'1 ####. ###. ###.',23
LM 14,12,12(13)
BR 14
LTORG
END |
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.
| #OCaml | OCaml | let write_file filename s =
let oc = open_out filename in
output_string oc s;
close_out oc;
;;
let () =
let filename = "test.txt" in
let s = String.init 26 (fun i -> char_of_int (i + int_of_char 'A')) in
write_file filename s |
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.
| #Pascal | Pascal | {$ifDef FPC}{$mode ISO}{$endIf}
program overwriteFile(FD);
begin
writeLn(FD, 'Whasup?');
close(FD);
end. |
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.
| #Perl | Perl | use File::Slurper 'write_text';
write_text($filename, $data); |
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program xiaolin1.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess displayerror
see at end oh this program the instruction include */
/* REMARK 2 : display use a FrameBuffer device : see raspberry pi FrameBuffer documentation
this solution write directly on the screen of raspberry pi
other solution is to use X11 windows but X11 has a function drawline !! */
/* REMARK 3 : this program do not respect the convention for use, save and restau registers
in rhe routine call !!!! */
/*******************************************/
/* Constantes */
/*******************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ OPEN, 5
.equ CLOSE, 6
.equ IOCTL, 0x36
.equ MMAP, 0xC0
.equ UNMAP, 0x5B
.equ O_RDWR, 0x0002 @ open for reading and writing
.equ MAP_SHARED, 0x01 @ Share changes.
.equ PROT_READ, 0x1 @ Page can be read.
.equ PROT_WRITE, 0x2 @ Page can be written.
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessErreur: .asciz "File open error.\n"
szMessErreur1: .asciz "File close error.\n"
szMessErreur2: .asciz "File mapping error.\n"
szMessDebutPgm: .asciz "Program start. \n"
szMessFinOK: .asciz "Normal end program. \n"
szMessErrFix: .asciz "Read error info fix framebuffer \n"
szMessErrVar: .asciz "Read error info var framebuffer \n"
szRetourligne: .asciz "\n"
szParamNom: .asciz "/dev/fb0" @ FrameBuffer device name
szLigneVar: .ascii "Variables info : "
sWidth: .fill 11, 1, ' '
.ascii " * "
sHeight: .fill 11, 1, ' '
.ascii " Bits par pixel : "
sBits: .fill 11, 1, ' '
.asciz "\n"
/*************************************************/
szMessErr: .ascii "Error code hexa : "
sHexa: .space 9,' '
.ascii " decimal : "
sDeci: .space 15,' '
.asciz "\n"
.align 4
/* codes fonction pour la récupération des données fixes et variables */
FBIOGET_FSCREENINFO: .int 0x4602 @ function code for read infos fixes Framebuffer
FBIOGET_VSCREENINFO: .int 0x4600 @ function code for read infos variables Framebuffer
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
.align 4
fix_info: .skip FBFIXSCinfo_fin @ memory reserve for structure FSCREENINFO
.align 4
var_info: .skip FBVARSCinfo_fin @ memory reserve for structure VSCREENINFO
/**********************************************/
/* -- Code section */
/**********************************************/
.text
.global main
main:
ldr r0,iAdrszMessDebutPgm
bl affichageMess @ display message
ldr r0,iAdrszParamNom @ frameBuffer device name
mov r1,#O_RDWR @ flags read/write
mov r2,#0 @ mode
mov r7,#OPEN @ open device FrameBuffer
svc 0
cmp r0,#0 @ error ?
ble erreur
mov r10,r0 @ save FD du device FrameBuffer in r10
ldr r1,iAdrFBIOGET_VSCREENINFO @ read variables datas of FrameBuffer
ldr r1,[r1] @ load code function
ldr r2,iAdrvar_info @ structure memory address
mov r7, #IOCTL @ call system
swi 0
cmp r0,#0
blt erreurVar
ldr r2,iAdrvar_info
ldr r0,[r2,#FBVARSCinfo_xres] @ load screen width
ldr r1,iAdrsWidth @ and convert in string for display
bl conversion10S
ldr r0,[r2,#FBVARSCinfo_yres] @ load screen height
ldr r1,iAdrsHeight @ and convert in string for display
bl conversion10S
ldr r0,[r2,#FBVARSCinfo_bits_per_pixel] @ load bits by pixel
ldr r1,iAdrsBits @ and convert in string for display
bl conversion10S
ldr r0,iAdrszLigneVar @ display result
bl affichageMess
mov r0,r10 @ FD du FB
ldr r1,iAdrFBIOGET_FSCREENINFO @ read fixes datas of FrameBuffe
ldr r1,[r1] @ load code function
ldr r2,iAdrfix_info @ structure memory address
mov r7, #IOCTL @ call system
svc 0
cmp r0,#0 @ error ?
blt erreurFix
ldr r0,iAdrfix_info
ldr r1,iAdrfix_info @ read size memory for datas
ldr r1,[r1,#FBFIXSCinfo_smem_len] @ in octets
@ datas mapping
mov r0,#0
ldr r2,iFlagsMmap
mov r3,#MAP_SHARED
mov r4,r10
mov r5,#0
mov r7, #MMAP @ 192 call system for mapping
swi #0
cmp r0,#0 @ error ?
beq erreur2
mov r9,r0 @ save mapping address in r9
/*************************************/
/* display draw */
bl dessin
/************************************/
mov r0,r9 @ mapping close
ldr r1,iAdrfix_info
ldr r1,[r1,#FBFIXSCinfo_smem_len] @ mapping memory size
mov r7,#UNMAP @call system 91 for unmapping
svc #0 @ error ?
cmp r0,#0
blt erreur1
@ close device FrameBuffer
mov r0,r10 @ load FB du device
mov r7, #CLOSE @ call system
swi 0
ldr r0,iAdrszMessFinOK @ display end message
bl affichageMess
mov r0,#0 @ return code = OK
b 100f
erreurFix: @ display read error datas fix
ldr r1,iAdrszMessErrFix @ message address
bl displayError @ call display
mov r0,#1 @ return code = error
b 100f
erreurVar: @ display read error datas var
ldr r1,iAdrszMessErrVar
bl displayError
mov r0,#1
b 100f
erreur: @ display open error
ldr r1,iAdrszMessErreur
bl displayError
mov r0,#1
b 100f
erreur1: @ display unmapped error
ldr r1,iAdrszMessErreur1
bl displayError
mov r0,#1
b 100f
erreur2: @ display mapped error
ldr r1,iAdrszMessErreur2
bl displayError
mov r0,#1
b 100f
100: @ end program
mov r7, #EXIT
svc 0
/************************************/
iAdrszParamNom: .int szParamNom
iFlagsMmap: .int PROT_READ|PROT_WRITE
iAdrszMessErreur: .int szMessErreur
iAdrszMessErreur1: .int szMessErreur1
iAdrszMessErreur2: .int szMessErreur2
iAdrszMessDebutPgm: .int szMessDebutPgm
iAdrszMessFinOK: .int szMessFinOK
iAdrszMessErrFix: .int szMessErrFix
iAdrszMessErrVar: .int szMessErrVar
iAdrszLigneVar: .int szLigneVar
iAdrvar_info: .int var_info
iAdrfix_info: .int fix_info
iAdrFBIOGET_FSCREENINFO: .int FBIOGET_FSCREENINFO
iAdrFBIOGET_VSCREENINFO: .int FBIOGET_VSCREENINFO
iAdrsWidth: .int sWidth
iAdrsHeight: .int sHeight
iAdrsBits: .int sBits
/***************************************************/
/* dessin */
/***************************************************/
/* r9 framebuffer memory address */
dessin:
push {r1-r12,lr} @ save registers
mov r0,#255 @ red
mov r1,#255 @ green
mov r2,#255 @ blue 3 bytes 255 = white
bl codeRGB @ code color RGB 32 bits
mov r1,r0 @ background color
ldr r0,iAdrfix_info @ load memory mmap size
ldr r0,[r0,#FBFIXSCinfo_smem_len]
bl coloriageFond @
/* draw line 1 */
mov r0,#200 @ X start line
mov r1,#200 @ Y start line
mov r2,#200 @ X end line
mov r3,#100 @ Y end line
ldr r4,iAdrvar_info
ldr r4,[r4,#FBVARSCinfo_xres] @ load screen width
bl drawLine
/* draw line 2 */
mov r0,#200
mov r1,#200
mov r2,#200
mov r3,#300
ldr r4,iAdrvar_info
ldr r4,[r4,#FBVARSCinfo_xres]
bl drawLine
/* draw line 3 */
mov r0,#200
mov r1,#200
mov r2,#100
mov r3,#200
ldr r4,iAdrvar_info
ldr r4,[r4,#FBVARSCinfo_xres]
bl drawLine
/* draw line 4 */
mov r0,#200
mov r1,#200
mov r2,#300
mov r3,#200
ldr r4,iAdrvar_info
ldr r4,[r4,#FBVARSCinfo_xres]
bl drawLine
/* draw line 5 */
mov r0,#200
mov r1,#200
mov r2,#100
mov r3,#100
ldr r4,iAdrvar_info
ldr r4,[r4,#FBVARSCinfo_xres]
bl drawLine
/* draw line 6 */
mov r0,#200
mov r1,#200
mov r2,#100
mov r3,#300
ldr r4,iAdrvar_info
ldr r4,[r4,#FBVARSCinfo_xres]
bl drawLine
/* draw line 7 */
mov r0,#200
mov r1,#200
mov r2,#300
mov r3,#300
ldr r4,iAdrvar_info
ldr r4,[r4,#FBVARSCinfo_xres]
bl drawLine
/* draw line 8 */
mov r0,#200
mov r1,#200
mov r2,#300
mov r3,#100
ldr r4,iAdrvar_info
ldr r4,[r4,#FBVARSCinfo_xres]
bl drawLine
100:
pop {r1-r12,lr} @ restaur registers
bx lr @ end function
/********************************************************/
/* set background color */
/********************************************************/
/* r0 contains size screen memory */
/* r1 contains rgb code color */
/* r9 contains screen memory address */
coloriageFond:
push {r2,lr}
mov r2,#0 @ counter
1: @ begin loop
str r1,[r9,r2]
add r2,#4
cmp r2,r0
blt 1b
pop {r2,lr}
bx lr
/********************************************************/
/* Xiaolin Wu line algorithm */
/* no floating point compute, multiply value for 128 */
/* for integer compute */
/********************************************************/
/* r0 x1 start line */
/* r1 y1 start line */
/* r2 x2 end line */
/* r3 y2 end line */
/* r4 screen width */
drawLine:
push {fp,lr} @ save registers ( no other registers save )
mov r5,r0 @ save x1
mov r6,r1 @ save y1
cmp r2,r5 @ compar x2,x1
subgt r1,r2,r5
suble r1,r5,r2 @ compute dx=abs val de x1-x2
cmp r3,r6 @ compar y2,y1
subgt r0,r3,r6
suble r0,r6,r3 @ compute dy = abs val de y1-y2
cmp r1,r0 @ compare dx , dy
blt 5f @ dx < dy
@ dx > dy
cmp r2,r5 @ compare x2,x1
movlt r8,r5 @ x2 < x1
movlt r5,r2 @ swap x2,x1
movlt r2,r8
movlt r8,r6 @ swap y2,y1
movlt r6,r3
movlt r3,r8
lsl r0,#7 @ * by 128
mov r7,r2 @ save x2
mov r8,r3 @ save y2
cmp r1,#0 @ divisor = 0 ?
moveq r10,#128
beq 1f
bl division @ gradient compute (* 128)
mov r10,r2 @ r10 contient le gradient
1:
@ display start points
mov r0,#64
bl colorPixel
mov r3,r0 @ RGB color
mov r0,r5 @ x1
mov r1,r6 @ y1
mov r2,r4 @ screen witdh
bl aff_pixel_codeRGB32 @ display pixel
add r1,#1 @ increment y1
bl aff_pixel_codeRGB32
@ display end points
mov r0,r7 @ x2
mov r1,r8 @ y2
bl aff_pixel_codeRGB32
add r1,#1 @ increment y2
bl aff_pixel_codeRGB32
cmp r8,r6 @ compar y2,y1
blt 3f @ y2 < y1
mov r4,r5 @ x = x1
lsl r5,r6,#7 @ compute y1 * 128
add r5,r10 @ compute intery = (y1 * 128 + gradient * 128)
2: @ start loop draw line pixels
lsr r1,r5,#7 @ intery / 128 = y
lsl r8,r1,#7
sub r6,r5,r8 @ reminder of intery /128 = brightness
mov r0,r6
bl colorPixel @ compute rgb color brightness
mov r3,r0 @ rgb color
mov r0,r4 @ x
bl aff_pixel_codeRGB32 @ display pixel 1
add r1,#1 @ increment y
rsb r0,r6,#128 @ compute 128 - brightness
bl colorPixel @ compute new rgb color
mov r3,r0
mov r0,r4
bl aff_pixel_codeRGB32 @ display pixel 2
add r5,r10 @ add gradient to intery
add r4,#1 @ increment x
cmp r4,r7 @ x < x2
ble 2b @ yes -> loop
b 100f @ else end
3: @ y2 < y1
mov r4,r7 @ x = x2
mov r7,r5 @ save x1
lsl r5,r8,#7 @ y = y1 * 128
add r5,r10 @ compute intery = (y1 * 128 + gradient * 128)
4:
lsr r1,r5,#7 @ y = ent(intery / 128)
lsl r8,r1,#7
sub r8,r5,r8 @ brightness = remainder
mov r0,r8
bl colorPixel
mov r3,r0
mov r0,r4
bl aff_pixel_codeRGB32
add r1,#1
rsb r0,r8,#128
bl colorPixel
mov r3,r0
mov r0,r4
bl aff_pixel_codeRGB32
add r5,r10
sub r4,#1 @ decrement x
cmp r4,r7 @ x > x1
bgt 4b @ yes -> loop
b 100f
5: @ dx < dy
cmp r3,r6 @ compare y2,y1
movlt r8,r5 @ y2 < y1
movlt r5,r2 @ swap x1,x2
movlt r2,r8
movlt r8,r6 @ swap y1,y2
movlt r6,r3
movlt r3,r8
mov r8,r1 @ swap r0,r1 for routine division
mov r1,r0
lsl r0,r8,#7 @ dx * by 128
mov r7,r2 @ save x2
mov r8,r3 @ save y2
cmp r1,#0 @ dy = zero ?
moveq r10,#128
beq 6f
bl division @ compute gradient * 128
mov r10,r2 @ gradient -> r10
6:
@ display start points
mov r0,#64
bl colorPixel
mov r3,r0 @ color pixel
mov r0,r5 @ x1
mov r1,r6 @ y1
mov r2,r4 @ screen width
bl aff_pixel_codeRGB32
add r1,#1
bl aff_pixel_codeRGB32
@ display end points
mov r0,r7
mov r1,r8
bl aff_pixel_codeRGB32
add r1,#1
bl aff_pixel_codeRGB32
cmp r5,r7 @ x1 < x2 ?
blt 8f
mov r4,r6 @ y = y1
lsl r5,#7 @ compute x1 * 128
add r5,r10 @ compute interx
7:
lsr r1,r5,#7 @ compute x = ent ( interx / 128)
lsl r3,r1,#7
sub r6,r5,r3 @ brightness = remainder
mov r0,r6
bl colorPixel
mov r3,r0
mov r0,r1 @ new x
add r7,r0,#1
mov r1,r4 @ y
bl aff_pixel_codeRGB32
rsb r0,r6,#128
bl colorPixel
mov r3,r0
mov r0,r7 @ new x + 1
mov r1,r4 @ y
bl aff_pixel_codeRGB32
add r5,r10
add r4,#1
cmp r4,r8
ble 7b
b 100f
8:
mov r4,r8 @ y = y2
lsl r5,#7 @ compute x1 * 128
add r5,r10 @ compute interx
9:
lsr r1,r5,#7 @ compute x
lsl r3,r1,#7
sub r8,r5,r3
mov r0,r8
bl colorPixel
mov r3,r0
mov r0,r1 @ new x
add r7,r0,#1
mov r1,r4 @ y
bl aff_pixel_codeRGB32
rsb r0,r8,#128
bl colorPixel
mov r3,r0
mov r0,r7 @ new x + 1
mov r1,r4 @ y
bl aff_pixel_codeRGB32
add r5,r10
sub r4,#1
cmp r4,r6
bgt 9b
b 100f
100:
pop {fp,lr}
bx lr
/********************************************************/
/* brightness color pixel */
/********************************************************/
/* r0 % brightness ( 0 to 128) */
colorPixel:
push {r1,r2,lr} /* save des 2 registres frame et retour */
cmp r0,#0
beq 100f
cmp r0,#128
mov r0,#127
lsl r0,#1 @ red = brightness * 2 ( 2 to 254)
mov r1,r0 @ green = red
mov r2,r0 @ blue = red
bl codeRGB @ compute rgb code color 32 bits
100:
pop {r1,r2,lr}
bx lr
/***************************************************/
/* display pixels 32 bits */
/***************************************************/
/* r9 framebuffer memory address */
/* r0 = x */
/* r1 = y */
/* r2 screen width in pixels */
/* r3 code color RGB 32 bits */
aff_pixel_codeRGB32:
push {r0-r4,lr} @ save registers
@ compute location pixel
mul r4,r1,r2 @ compute y * screen width
add r0,r0,r4 @ + x
lsl r0,#2 @ * 4 octets
str r3,[r9,r0] @ store rgb code in mmap memory
pop {r0-r4,lr} @ restaur registers
bx lr
/********************************************************/
/* Code color RGB */
/********************************************************/
/* r0 red r1 green r2 blue */
/* r0 returns RGB code */
codeRGB:
lsl r0,#16 @ shift red color 16 bits
lsl r1,#8 @ shift green color 8 bits
eor r0,r1 @ or two colors
eor r0,r2 @ or 3 colors in r0
bx lr
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "./affichage.inc"
/***************************************************/
/* DEFINITION DES STRUCTURES */
/***************************************************/
/* structure FSCREENINFO */
/* voir explication détaillée : https://www.kernel.org/doc/Documentation/fb/api.txt */
.struct 0
FBFIXSCinfo_id: /* identification string eg "TT Builtin" */
.struct FBFIXSCinfo_id + 16
FBFIXSCinfo_smem_start: /* Start of frame buffer mem */
.struct FBFIXSCinfo_smem_start + 4
FBFIXSCinfo_smem_len: /* Length of frame buffer mem */
.struct FBFIXSCinfo_smem_len + 4
FBFIXSCinfo_type: /* see FB_TYPE_* */
.struct FBFIXSCinfo_type + 4
FBFIXSCinfo_type_aux: /* Interleave for interleaved Planes */
.struct FBFIXSCinfo_type_aux + 4
FBFIXSCinfo_visual: /* see FB_VISUAL_* */
.struct FBFIXSCinfo_visual + 4
FBFIXSCinfo_xpanstep: /* zero if no hardware panning */
.struct FBFIXSCinfo_xpanstep + 2
FBFIXSCinfo_ypanstep: /* zero if no hardware panning */
.struct FBFIXSCinfo_ypanstep + 2
FBFIXSCinfo_ywrapstep: /* zero if no hardware ywrap */
.struct FBFIXSCinfo_ywrapstep + 4
FBFIXSCinfo_line_length: /* length of a line in bytes */
.struct FBFIXSCinfo_line_length + 4
FBFIXSCinfo_mmio_start: /* Start of Memory Mapped I/O */
.struct FBFIXSCinfo_mmio_start + 4
FBFIXSCinfo_mmio_len: /* Length of Memory Mapped I/O */
.struct FBFIXSCinfo_mmio_len + 4
FBFIXSCinfo_accel: /* Indicate to driver which specific chip/card we have */
.struct FBFIXSCinfo_accel + 4
FBFIXSCinfo_capabilities: /* see FB_CAP_* */
.struct FBFIXSCinfo_capabilities + 4
FBFIXSCinfo_reserved: /* Reserved for future compatibility */
.struct FBFIXSCinfo_reserved + 8
FBFIXSCinfo_fin:
/* structure VSCREENINFO */
.struct 0
FBVARSCinfo_xres: /* visible resolution */
.struct FBVARSCinfo_xres + 4
FBVARSCinfo_yres:
.struct FBVARSCinfo_yres + 4
FBVARSCinfo_xres_virtual: /* virtual resolution */
.struct FBVARSCinfo_xres_virtual + 4
FBVARSCinfo_yres_virtual:
.struct FBVARSCinfo_yres_virtual + 4
FBVARSCinfo_xoffset: /* offset from virtual to visible resolution */
.struct FBVARSCinfo_xoffset + 4
FBVARSCinfo_yoffset:
.struct FBVARSCinfo_yoffset + 4
FBVARSCinfo_bits_per_pixel: /* bits par pixel */
.struct FBVARSCinfo_bits_per_pixel + 4
FBVARSCinfo_grayscale: /* 0 = color, 1 = grayscale, >1 = FOURCC */
.struct FBVARSCinfo_grayscale + 4
FBVARSCinfo_red: /* bitfield in fb mem if true color, */
.struct FBVARSCinfo_red + 4
FBVARSCinfo_green: /* else only length is significant */
.struct FBVARSCinfo_green + 4
FBVARSCinfo_blue:
.struct FBVARSCinfo_blue + 4
FBVARSCinfo_transp: /* transparency */
.struct FBVARSCinfo_transp + 4
FBVARSCinfo_nonstd: /* != 0 Non standard pixel format */
.struct FBVARSCinfo_nonstd + 4
FBVARSCinfo_activate: /* see FB_ACTIVATE_* */
.struct FBVARSCinfo_activate + 4
FBVARSCinfo_height: /* height of picture in mm */
.struct FBVARSCinfo_height + 4
FBVARSCinfo_width: /* width of picture in mm */
.struct FBVARSCinfo_width + 4
FBVARSCinfo_accel_flags: /* (OBSOLETE) see fb_info.flags */
.struct FBVARSCinfo_accel_flags + 4
/* Timing: All values in pixclocks, except pixclock (of course) */
FBVARSCinfo_pixclock: /* pixel clock in ps (pico seconds) */
.struct FBVARSCinfo_pixclock + 4
FBVARSCinfo_left_margin:
.struct FBVARSCinfo_left_margin + 4
FBVARSCinfo_right_margin:
.struct FBVARSCinfo_right_margin + 4
FBVARSCinfo_upper_margin:
.struct FBVARSCinfo_upper_margin + 4
FBVARSCinfo_lower_margin:
.struct FBVARSCinfo_lower_margin + 4
FBVARSCinfo_hsync_len: /* length of horizontal sync */
.struct FBVARSCinfo_hsync_len + 4
FBVARSCinfo_vsync_len: /* length of vertical sync */
.struct FBVARSCinfo_vsync_len + 4
FBVARSCinfo_sync: /* see FB_SYNC_* */
.struct FBVARSCinfo_sync + 4
FBVARSCinfo_vmode: /* see FB_VMODE_* */
.struct FBVARSCinfo_vmode + 4
FBVARSCinfo_rotate: /* angle we rotate counter clockwise */
.struct FBVARSCinfo_rotate + 4
FBVARSCinfo_colorspace: /* colorspace for FOURCC-based modes */
.struct FBVARSCinfo_colorspace + 4
FBVARSCinfo_reserved: /* Reserved for future compatibility */
.struct FBVARSCinfo_reserved + 16
FBVARSCinfo_fin:
|
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 > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & 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.
| #ALGOL_68 | ALGOL 68 | # returns a translation of str suitable for attribute values and content in an XML document #
OP TOXMLSTRING = ( STRING str )STRING:
BEGIN
STRING result := "";
FOR pos FROM LWB str TO UPB str DO
CHAR c = str[ pos ];
result +:= IF c = "<" THEN "<"
ELIF c = ">" THEN ">"
ELIF c = "&" THEN "&"
ELIF c = "'" THEN "'"
ELIF c = """" THEN """
ELSE c
FI
OD;
result
END; # TOXMLSTRING #
# generate a CharacterRemarks XML document from the characters and remarks #
# the number of elements in characters and remrks must be equal - this is not checked #
# the <?xml?> element is not generated #
PROC generate character remarks document = ( []STRING characters, remarks )STRING:
BEGIN
STRING result := "<CharacterRemarks>";
INT remark pos := LWB remarks;
FOR char pos FROM LWB characters TO UPB characters DO
result +:= "<Character name=""" + TOXMLSTRING characters[ char pos ] + """>"
+ TOXMLSTRING remarks[ remark pos ]
+ "</Character>"
+ REPR 10
;
remark pos +:= 1
OD;
result +:= "</CharacterRemarks>";
result
END; # generate character remarks document #
# test the generation #
print( ( generate character remarks document( ( "April", "Tam O'Shanter", "Emily" )
, ( "Bubbly: I'm > Tam and <= Emily"
, "Burns: ""When chapman billies leave the street ..."
, "Short & shrift"
)
)
, newline
)
)
|
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="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program inputXml.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ XML_ELEMENT_NODE, 1
.equ XML_ATTRIBUTE_NODE, 2
.equ XML_TEXT_NODE, 3
.equ XML_CDATA_SECTION_NODE, 4
.equ XML_ENTITY_REF_NODE, 5
.equ XML_ENTITY_NODE, 6
.equ XML_PI_NODE, 7
.equ XML_COMMENT_NODE, 8
.equ XML_DOCUMENT_NODE, 9
.equ XML_DOCUMENT_TYPE_NODE, 10
.equ XML_DOCUMENT_FRAG_NODE, 11
.equ XML_NOTATION_NODE, 12
.equ XML_HTML_DOCUMENT_NODE, 13
.equ XML_DTD_NODE, 14
.equ XML_ELEMENT_DECL, 15
.equ XML_ATTRIBUTE_DECL, 16
.equ XML_ENTITY_DECL, 17
.equ XML_NAMESPACE_DECL, 18
.equ XML_XINCLUDE_START, 19
.equ XML_XINCLUDE_END, 20
.equ XML_DOCB_DOCUMENT_NODE 21
/*******************************************/
/* Structures */
/********************************************/
/* structure linkedlist*/
.struct 0
xmlNode_private: @ application data
.struct xmlNode_private + 4
xmlNode_type: @ type number, must be second !
.struct xmlNode_type + 4
xmlNode_name: @ the name of the node, or the entity
.struct xmlNode_name + 4
xmlNode_children: @ parent->childs link
.struct xmlNode_children + 4
xmlNode_last: @ last child link
.struct xmlNode_last + 4
xmlNode_parent: @ child->parent link
.struct xmlNode_parent + 4
xmlNode_next: @ next sibling link
.struct xmlNode_next + 4
xmlNode_prev: @ previous sibling link
.struct xmlNode_prev + 4
xmlNode_doc: @ the containing document
.struct xmlNode_doc + 4
xmlNode_ns: @ pointer to the associated namespace
.struct xmlNode_ns + 4
xmlNode_content: @ the content
.struct xmlNode_content + 4
xmlNode_properties: @ properties list
.struct xmlNode_properties + 4
xmlNode_nsDef: @ namespace definitions on this node
.struct xmlNode_nsDef + 4
xmlNode_psvi: @ for type/PSVI informations
.struct xmlNode_psvi + 4
xmlNode_line: @ line number
.struct xmlNode_line + 4
xmlNode_extra: @ extra data for XPath/XSLT
.struct xmlNode_extra + 4
xmlNode_fin:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndpgm: .asciz "Normal end of program.\n"
szMessError: .asciz "Error detected !!!!. \n"
szText: .ascii "<Students>\n"
.ascii "<Student Name=\"April\" Gender=\"F\" DateOfBirth=\"1989-01-02\" />\n"
.ascii "<Student Name=\"Bob\" Gender=\"M\" DateOfBirth=\"1990-03-04\" />\n"
.ascii "<Student Name=\"Chad\" Gender=\"M\" DateOfBirth=\"1991-05-06\" />\n"
.ascii "<Student Name=\"Dave\" Gender=\"M\" DateOfBirth=\"1992-07-08\">\n"
.ascii "<Pet Type=\"dog\" Name=\"Rover\" />\n"
.ascii "</Student>\n"
.ascii "<Student DateOfBirth=\"1993-09-10\" Gender=\"F\" Name=\"Émily\" />\n"
.asciz "</Students>"
.equ LGSZTEXT, . - szText @ compute text size (. is current address)
szLibExtract: .asciz "Student"
szLibName: .asciz "Name"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszText @ text buffer
mov r1,#LGSZTEXT @ text size
mov r2,#0 @ param 3
mov r3,#0 @ param 4
mov r4,#0 @ param 5
sub sp,#4 @ stack assignement
push {r4} @ param 5 on stack
bl xmlReadMemory @ read text in document
add sp,#8 @ stack assignement for 1 push and align stack
cmp r0,#0 @ error ?
beq 1f
mov r9,r0 @ doc address
mov r0,r9
bl xmlDocGetRootElement @ search root return in r0
bl affElement @ display elements
mov r0,r9
bl xmlFreeDoc
1:
bl xmlCleanupParser
ldr r0,iAdrszMessEndpgm
bl affichageMess
b 100f
99:
@ error
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszMessError: .int szMessError
iAdrszMessEndpgm: .int szMessEndpgm
iAdrszText: .int szText
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display name of student */
/******************************************************************/
/* r0 contains the address of node */
affElement:
push {r1-r4,lr} @ save registres
mov r4,r0 @ save node
1:
ldr r2,[r4,#xmlNode_type] @ type ?
cmp r2,#XML_ELEMENT_NODE
bne 2f
ldr r0,[r4,#xmlNode_name] @ name = "Student" ?
ldr r1,iAdrszLibExtract
bl comparString
cmp r0,#0
bne 2f @ no
mov r0,r4
ldr r1,iAdrszLibName @ load property of "Name"
bl xmlHasProp
cmp r0,#0
beq 2f
ldr r1,[r0,#xmlNode_children] @ children node of property name
ldr r0,[r1,#xmlNode_content] @ and address of content
bl affichageMess @ for display
ldr r0,iAdrszCarriageReturn
bl affichageMess
2:
ldr r0,[r4,#xmlNode_children] @ node have children ?
cmp r0,#0
blne affElement @ yes -> call procedure
ldr r1,[r4,#xmlNode_next] @ other element ?
cmp r1,#0
beq 100f @ no -> end procedure
mov r4,r1 @ else loop with next element
b 1b
100:
pop {r1-r4,lr} @ restaur registers */
bx lr @ return
iAdrszLibName: .int szLibName
iAdrszLibExtract: .int szLibExtract
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur registers */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ previous position
bne 1b @ else loop
@ end replaces digit in front of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4] @ store in area begin
add r4,#1
add r2,#1 @ previous position
cmp r2,#LGZONECAL @ end
ble 2b @ loop
mov r1,#' '
3:
strb r1,[r3,r4]
add r4,#1
cmp r4,#LGZONECAL @ end
ble 3b
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} @ save registers */
mov r4,r0
mov r3,#0x6667 @ r3 <- magic_number lower
movt r3,#0x6666 @ r3 <- magic_number upper
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
mov r2, r2, ASR #2 @ r2 <- r2 >> 2
mov r1, r0, LSR #31 @ r1 <- r0 >> 31
add r0, r2, r1 @ r0 <- r2 + r1
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2-r4}
bx lr @ return
/************************************/
/* comparaison de chaines */
/************************************/
/* r0 et r1 contiennent les adresses des chaines */
/* retour 0 dans r0 si egalite */
/* retour -1 si chaine r0 < chaine r1 */
/* retour 1 si chaine r0> chaine r1 */
comparString:
push {r1-r4} @ save des registres
mov r2,#0 @ indice
1:
ldrb r3,[r0,r2] @ octet chaine 1
ldrb r4,[r1,r2] @ octet chaine 2
cmp r3,r4
movlt r0,#-1 @ plus petite
movgt r0,#1 @ plus grande
bne 100f @ pas egaux
cmp r3,#0 @ 0 final
moveq r0,#0 @ egalite
beq 100f @ c est la fin
add r2,r2,#1 @ sinon plus 1 dans indice
b 1b @ et boucle
100:
pop {r1-r4}
bx lr
|
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)
| #Scratch | Scratch | $ include "seed7_05.s7i";
const type: charArray is array [char] string; # Define an array type for arrays with char index.
const type: twoDim is array array char; # Define an array type for a two dimensional array.
const proc: main is func
local
var array integer: array1 is 10 times 0; # Array with 10 elements of 0.
var array boolean: array2 is [0 .. 4] times TRUE; # Array with 5 elements of TRUE.
var array integer: array3 is [] (1, 2, 3, 4); # Array with the elements 1, 2, 3, 4.
var array string: array4 is [] ("foo", "bar"); # Array with string elements.
var array char: array5 is [0] ('a', 'b', 'c'); # Array with indices starting from 0.
const array integer: array6 is [] (2, 3, 5, 7, 11); # Array constant.
var charArray: array7 is ['1'] ("one", "two"); # Array with char index starting from '1'.
var twoDim: array8 is [] ([] ('a', 'b'), # Define two dimensional array.
[] ('A', 'B'));
begin
writeln(length(array1)); # Get array length (= number of array elements).
writeln(length(array2)); # Writes 5, because array2 has 5 array elements.
writeln(array4[2]); # Get array element ("bar"). By default array indices start from 1.
writeln(array5[1]); # Writes b, because the indices of array5 start from 0.
writeln(array7['2']); # Writes two, because the indices of array7 start from '1'.
writeln(array8[2][2]); # Writes B, because both indices start from 1.
writeln(minIdx(array7)); # Get minumum index of array ('1').
array3[1] := 5; # Replace element. Now array3 has the elements 5, 2, 3, 4.
writeln(remove(array3, 3)); # Remove 3rd element. Now array3 has the elements 5, 2, 4.
array1 := array6; # Assign a whole array.
array1 &:= [] (13, 17); # Append an array.
array1 &:= 19; # Append an element.
array1 := array3[2 ..]; # Assign a slice beginning with the second element.
array1 := array3[.. 5]; # Assign a slice up to the fifth element.
array1 := array3[3 .. 4]; # Assign a slice from the third to the fourth element.
array1 := array3[2 len 4]; # Assign a slice of four elements beginning with the second element.
array1 := array3 & array6; # Concatenate two arrays and assign the result to array1.
end func; |
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.
| #Common_Lisp | Common Lisp | (defun histo ()
(let ((scoring (vector 0 1 3))
(histo (list (vector 0 0 0 0 0 0 0 0 0 0) (vector 0 0 0 0 0 0 0 0 0 0)
(vector 0 0 0 0 0 0 0 0 0 0) (vector 0 0 0 0 0 0 0 0 0 0)))
(team-combs (vector '(0 1) '(0 2) '(0 3) '(1 2) '(1 3) '(2 3)))
(single-tupel)
(sum))
; six nested dotimes produces the tupels of the cartesian product of
; six lists like '(0 1 2), but without to store all tuples in a list
(dotimes (x0 3) (dotimes (x1 3) (dotimes (x2 3)
(dotimes (x3 3) (dotimes (x4 3) (dotimes (x5 3)
(setf single-tupel (vector x0 x1 x2 x3 x4 x5))
(setf sum (vector 0 0 0 0))
(dotimes (i (length single-tupel))
(setf (elt sum (first (elt team-combs i)))
(+ (elt sum (first (elt team-combs i)))
(elt scoring (elt single-tupel i))))
(setf (elt sum (second (elt team-combs i)))
(+ (elt sum (second (elt team-combs i)))
(elt scoring (- 2 (elt single-tupel i))))))
(dotimes (i (length (sort sum #'<)))
(setf (elt (nth i histo) (elt sum i))
(1+ (elt (nth i histo) (elt sum i)))))
))))))
(reverse histo)))
; friendly output
(dolist (el (histo))
(dotimes (i (length el))
(format t "~3D " (aref el i)))
(format 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.
| #Fortran | Fortran | program writefloats
implicit none
real, dimension(10) :: a, sqrta
integer :: i
integer, parameter :: unit = 40
a = (/ (i, i=1,10) /)
sqrta = sqrt(a)
open(unit, file="xydata.txt", status="new", action="write")
call writexy(unit, a, sqrta)
close(unit)
contains
subroutine writexy(u, x, y)
real, dimension(:), intent(in) :: x, y
integer, intent(in) :: u
integer :: i
write(u, "(2F10.4)") (x(i), y(i), i=lbound(x,1), ubound(x,1))
end subroutine writexy
end program writefloats |
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.
| #Lua | Lua | local is_open = {}
for pass = 1,100 do
for door = pass,100,pass do
is_open[door] = not is_open[door]
end
end
for i,v in next,is_open do
print ('Door '..i..':',v and 'open' or 'close')
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>
| #JavaScript | JavaScript | var doc = document.implementation.createDocument( null, 'root', null );
var root = doc.documentElement;
var element = doc.createElement( 'element' );
root.appendChild( element );
element.appendChild( document.createTextNode('Some text here') );
var xmlString = new XMLSerializer().serializeToString( doc ); |
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>
| #Julia | Julia | using LightXML
# Modified from the documentation for LightXML.jl. The underlying library requires an encoding string be printed.
# create an empty XML document
xdoc = XMLDocument()
# create & attach a root node
xroot = create_root(xdoc, "root")
# create the first child
xs1 = new_child(xroot, "element")
# add the inner content
add_text(xs1, "some text here")
println(xdoc)
|
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
| #Action.21 | Action! | BYTE ARRAY data = [
$00 $00 $00 $00 $4E $4E $4E $00 $00 $00 $00 $00 $00 $00 $00 $00 $4E $00 $00 $00 $00 $4E $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $4E $00 $00 $00
$00 $00 $00 $46 $47 $00 $00 $47 $00 $00 $00 $00 $00 $00 $00 $42 $47 $47 $00 $00 $42 $47 $47 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $00 $42 $47 $47 $00 $00
$00 $00 $42 $47 $48 $80 $80 $80 $4A $00 $00 $4E $4E $4E $00 $42 $00 $80 $4E $00 $00 $47 $80 $00 $00 $4E $4E $00 $00 $00 $4E $4E $4E $00 $00 $42 $00 $80 $00 $00
$00 $00 $42 $00 $80 $00 $42 $00 $80 $00 $46 $47 $00 $00 $47 $42 $00 $80 $00 $47 $00 $4E $00 $00 $46 $47 $00 $47 $00 $42 $47 $00 $00 $47 $00 $42 $00 $80 $00 $00
$00 $00 $42 $00 $80 $00 $42 $00 $80 $42 $47 $48 $80 $80 $80 $42 $00 $80 $80 $80 $42 $47 $47 $42 $47 $48 $80 $80 $4A $42 $00 $80 $80 $80 $4A $42 $00 $80 $00 $00
$00 $00 $42 $00 $80 $4D $4D $47 $80 $42 $00 $80 $00 $00 $00 $42 $00 $80 $00 $00 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $00 $00
$00 $00 $42 $00 $80 $80 $80 $80 $80 $42 $00 $80 $00 $00 $00 $42 $00 $80 $00 $00 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $00 $47 $80 $00 $00
$00 $00 $42 $00 $80 $00 $42 $00 $80 $42 $00 $80 $4E $4E $00 $42 $00 $80 $4E $00 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $42 $00 $80 $00 $4E $00 $00 $00
$00 $00 $42 $00 $80 $00 $42 $00 $80 $00 $47 $80 $00 $00 $47 $00 $47 $80 $00 $47 $42 $00 $80 $00 $47 $80 $4D $47 $80 $42 $00 $80 $42 $00 $80 $42 $47 $47 $00 $00
$00 $00 $00 $47 $80 $00 $00 $47 $80 $00 $00 $CA $80 $80 $80 $00 $00 $CA $80 $80 $00 $47 $80 $00 $00 $CA $80 $80 $C8 $00 $47 $80 $00 $47 $80 $00 $47 $80 $00 $00]
PROC Main()
BYTE POINTER ptr
Graphics(0)
SetColor(2,0,2)
ptr=PeekC(88)+280
MoveBlock(ptr,data,400)
RETURN |
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.
| #Phix | Phix | without js -- (file i/o)
integer res = write_lines("file.txt",{"line 1\nline 2"})
if res=-1 then crash("error") end if
|
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.
| #PHP | PHP | file_put_contents($filename, $data) |
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.
| #AutoHotkey | AutoHotkey | #SingleInstance, Force
#NoEnv
SetBatchLines, -1
pToken := Gdip_Startup()
global pBitmap := Gdip_CreateBitmap(500, 500)
drawLine(100,50,400,400)
Gdip_SaveBitmapToFile(pBitmap, A_ScriptDir "\linetest.png")
Gdip_DisposeImage(pBitmap)
Gdip_Shutdown(pToken)
Run, % A_ScriptDir "\linetest.png"
ExitApp
plot(x, y, c) {
A := DecToBase(255 * c, 16)
Gdip_SetPixel(pBitmap, x, y, "0x" A "000000")
}
; integer part of x
ipart(x) {
return x // 1
}
rnd(x) {
return ipart(x + 0.5)
}
; fractional part of x
fpart(x) {
if (x < 0)
return 1 - (x - floor(x))
return x - floor(x)
}
rfpart(x) {
return 1 - fpart(x)
}
drawLine(x0,y0,x1,y1) {
steep := abs(y1 - y0) > abs(x1 - x0)
if (steep) {
temp := x0, x0 := y0, y0 := temp
temp := x1, x1 := y1, y1 := temp
}
if (x0 > x1 then) {
temp := x0, x0 := x1, x1 := temp
temp := y0, y0 := y1, y1 := temp
}
dx := x1 - x0
dy := y1 - y0
gradient := dy / dx
; handle first endpoint
xend := rnd(x0)
yend := y0 + gradient * (xend - x0)
xgap := rfpart(x0 + 0.5)
xpxl1 := xend ; this will be used in the main loop
ypxl1 := ipart(yend)
if (steep) {
plot(ypxl1, xpxl1, rfpart(yend) * xgap)
plot(ypxl1+1, xpxl1, fpart(yend) * xgap)
}
else {
plot(xpxl1, ypxl1 , rfpart(yend) * xgap)
plot(xpxl1, ypxl1+1, fpart(yend) * xgap)
}
intery := yend + gradient ; first y-intersection for the main loop
; handle second endpoint
xend := rnd(x1)
yend := y1 + gradient * (xend - x1)
xgap := fpart(x1 + 0.5)
xpxl2 := xend ;this will be used in the main loop
ypxl2 := ipart(yend)
if (steep) {
plot(ypxl2 , xpxl2, rfpart(yend) * xgap)
plot(ypxl2+1, xpxl2, fpart(yend) * xgap)
}
else {
plot(xpxl2, ypxl2, rfpart(yend) * xgap)
plot(xpxl2, ypxl2+1, fpart(yend) * xgap)
}
; main loop
while (x := xpxl1 + A_Index) < xpxl2 {
if (steep) {
plot(ipart(intery) , x, rfpart(intery))
plot(ipart(intery)+1, x, fpart(intery))
}
else {
plot(x, ipart (intery), rfpart(intery))
plot(x, ipart (intery)+1, fpart(intery))
}
intery := intery + gradient
}
}
DecToBase(n, Base) {
static U := A_IsUnicode ? "w" : "a"
VarSetCapacity(S,65,0)
DllCall("msvcrt\_i64to" U, "Int64",n, "Str",S, "Int",Base)
return, S
} |
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 > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & 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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program outputXml.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndpgm: .asciz "Normal end of program.\n"
szFileName: .asciz "file2.xml"
szFileMode: .asciz "w"
szMessError: .asciz "Error detected !!!!. \n"
szName1: .asciz "April"
szName2: .asciz "Tam O'Shanter"
szName3: .asciz "Emily"
szRemark1: .asciz "Bubbly: I'm > Tam and <= Emily"
szRemark2: .asciz "Burns: \"When chapman billies leave the street ...\""
szRemark3: .asciz "Short & shrift"
szVersDoc: .asciz "1.0"
szLibCharRem: .asciz "CharacterRemarks"
szLibChar: .asciz "Character"
//szLibExtract: .asciz "Student"
szLibName: .asciz "Name"
szCarriageReturn: .asciz "\n"
tbNames: .int szName1 @ area of pointer string name
.int szName2
.int szName3
.int 0 @ area end
tbRemarks: .int szRemark1 @ area of pointer string remark
.int szRemark2
.int szRemark3
.int 0 @ area end
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszVersDoc
bl xmlNewDoc @ create doc
mov r9,r0 @ doc address
mov r0,#0
ldr r1,iAdrszLibCharRem
bl xmlNewNode @ create root node
mov r8,r0 @ node characterisation address
mov r0,r9 @ doc
mov r1,r8 @ node root
bl xmlDocSetRootElement
ldr r4,iAdrtbNames
ldr r5,iAdrtbRemarks
mov r6,#0 @ loop counter
1: @ start loop
mov r0,#0
ldr r1,iAdrszLibChar @ create node
bl xmlNewNode
mov r7,r0 @ node character
@ r0 = node address
ldr r1,iAdrszLibName
ldr r2,[r4,r6,lsl #2] @ load name string address
bl xmlNewProp
ldr r0,[r5,r6,lsl #2] @ load remark string address
bl xmlNewText
mov r1,r0
mov r0,r7
bl xmlAddChild
mov r0,r8
mov r1,r7
bl xmlAddChild
add r6,#1
ldr r2,[r4,r6,lsl #2] @ load name string address
cmp r2,#0 @ = zero ?
bne 1b @ no -> loop
ldr r0,iAdrszFileName
ldr r1,iAdrszFileMode
bl fopen @ file open
cmp r0,#0
blt 99f
mov r6,r0 @FD
mov r1,r9
mov r2,r8
bl xmlDocDump @ write doc on the file
mov r0,r6
bl fclose
mov r0,r9
bl xmlFreeDoc
bl xmlCleanupParser
ldr r0,iAdrszMessEndpgm
bl affichageMess
b 100f
99:
@ error
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszMessError: .int szMessError
iAdrszMessEndpgm: .int szMessEndpgm
iAdrszVersDoc: .int szVersDoc
iAdrszLibCharRem: .int szLibCharRem
iAdrszLibChar: .int szLibChar
iAdrszLibName: .int szLibName
iAdrtbNames: .int tbNames
iAdrtbRemarks: .int tbRemarks
iAdrszCarriageReturn: .int szCarriageReturn
iStdout: .int STDOUT
iAdrszFileName: .int szFileName
iAdrszFileMode: .int szFileMode
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur registers */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal */
/******************************************************************/
/* r0 contains value and r1 address area */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ previous position
bne 1b @ else loop
@ end replaces digit in front of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4] @ store in area begin
add r4,#1
add r2,#1 @ previous position
cmp r2,#LGZONECAL @ end
ble 2b @ loop
mov r1,#' '
3:
strb r1,[r3,r4]
add r4,#1
cmp r4,#LGZONECAL @ end
ble 3b
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} @ save registers */
mov r4,r0
mov r3,#0x6667 @ r3 <- magic_number lower
movt r3,#0x6666 @ r3 <- magic_number upper
smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0)
mov r2, r2, ASR #2 @ r2 <- r2 >> 2
mov r1, r0, LSR #31 @ r1 <- r0 >> 31
add r0, r2, r1 @ r0 <- r2 + r1
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2-r4}
bx lr @ return
|
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #Arturo | Arturo | data: {
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
}
students: read.xml data
print join.with:"\n" map students 'student -> student\Name |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const type: charArray is array [char] string; # Define an array type for arrays with char index.
const type: twoDim is array array char; # Define an array type for a two dimensional array.
const proc: main is func
local
var array integer: array1 is 10 times 0; # Array with 10 elements of 0.
var array boolean: array2 is [0 .. 4] times TRUE; # Array with 5 elements of TRUE.
var array integer: array3 is [] (1, 2, 3, 4); # Array with the elements 1, 2, 3, 4.
var array string: array4 is [] ("foo", "bar"); # Array with string elements.
var array char: array5 is [0] ('a', 'b', 'c'); # Array with indices starting from 0.
const array integer: array6 is [] (2, 3, 5, 7, 11); # Array constant.
var charArray: array7 is ['1'] ("one", "two"); # Array with char index starting from '1'.
var twoDim: array8 is [] ([] ('a', 'b'), # Define two dimensional array.
[] ('A', 'B'));
begin
writeln(length(array1)); # Get array length (= number of array elements).
writeln(length(array2)); # Writes 5, because array2 has 5 array elements.
writeln(array4[2]); # Get array element ("bar"). By default array indices start from 1.
writeln(array5[1]); # Writes b, because the indices of array5 start from 0.
writeln(array7['2']); # Writes two, because the indices of array7 start from '1'.
writeln(array8[2][2]); # Writes B, because both indices start from 1.
writeln(minIdx(array7)); # Get minumum index of array ('1').
array3[1] := 5; # Replace element. Now array3 has the elements 5, 2, 3, 4.
writeln(remove(array3, 3)); # Remove 3rd element. Now array3 has the elements 5, 2, 4.
array1 := array6; # Assign a whole array.
array1 &:= [] (13, 17); # Append an array.
array1 &:= 19; # Append an element.
array1 := array3[2 ..]; # Assign a slice beginning with the second element.
array1 := array3[.. 5]; # Assign a slice up to the fifth element.
array1 := array3[3 .. 4]; # Assign a slice from the third to the fourth element.
array1 := array3[2 len 4]; # Assign a slice of four elements beginning with the second element.
array1 := array3 & array6; # Concatenate two arrays and assign the result to array1.
end func; |
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.
| #D | D | void main() {
import std.stdio, std.range, std.array, std.algorithm, combinations3;
immutable scoring = [0, 1, 3];
/*immutable*/ auto r3 = [0, 1, 2];
immutable combs = 4.iota.array.combinations(2).array;
uint[10][4] histo;
foreach (immutable results; cartesianProduct(r3, r3, r3, r3, r3, r3)) {
int[4] s;
foreach (immutable r, const g; [results[]].zip(combs)) {
s[g[0]] += scoring[r];
s[g[1]] += scoring[2 - r];
}
foreach (immutable i, immutable v; s[].sort().release)
histo[i][v]++;
}
writefln("%(%s\n%)", histo[].retro);
} |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Dim x(0 To 3) As Double = {1, 2, 3, 1e11}
Dim y(0 To 3) As Double = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}
Open "output.txt" For Output As #1
For i As Integer = 0 To 2
Print #1, Using "#"; x(i);
Print #1, Spc(7); Using "#.####"; y(i)
Next
Print #1, Using "#^^^^"; x(3);
Print #1, Spc(2); Using "##.####^^^^"; y(3)
Close #1 |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Doors100 {
Dim Doors(1 to 100)
For i=1 to 100
For j=i to 100 step i
Doors(j)~
Next j
Next i
DispAll()
' optimization
Dim Doors(1 to 100)=False
For i=1 to 10
Doors(i**2)=True
Next i
Print
DispAll()
Sub DispAll()
Local i
For i=1 to 100
if Doors(i) then print i,
Next i
Print
End Sub
}
Doors100
|
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>
| #Kotlin | Kotlin | // version 1.1.3
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.dom.DOMSource
import java.io.StringWriter
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.TransformerFactory
fun main(args: Array<String>) {
val dbFactory = DocumentBuilderFactory.newInstance()
val dBuilder = dbFactory.newDocumentBuilder()
val doc = dBuilder.newDocument()
val root = doc.createElement("root") // create root node
doc.appendChild(root)
val element = doc.createElement("element") // create element node
val text = doc.createTextNode("Some text here") // create text node
element.appendChild(text)
root.appendChild(element)
// serialize
val source = DOMSource(doc)
val sw = StringWriter()
val result = StreamResult(sw)
val tFactory = TransformerFactory.newInstance()
tFactory.newTransformer().apply {
setOutputProperty("indent", "yes")
setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4")
transform(source, result)
}
println(sw)
} |
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure AsciiArt is
art : constant array(1..27) of String(1..14) :=
(1=>" /\\\\\\ ", 2=>" /\\\",
3|6|9=>" ", 4|12=>" /\\\\\\\\\\ ",
5|8|11=>" \/\\\", 7|17|21=>" /\\\//////\\\",
10|19|20|22=>"\/\\\ \/\\\", 13|23|24=>"\/\\\\\\\\\\\\",
14|18=>" /\\\\\\\\\\\", 15=>" \/////////\\\",
16=>"\/\\\//////\\\", 25=>"\/// \/// ",
26|27=>"\//////////// ");
begin
for i in art'Range loop
Put(art(i)&' ');
if i mod 3 = 0 then New_Line; Put(i/3*' '); end if;
end loop;
end AsciiArt; |
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.
| #PicoLisp | PicoLisp | (out "file.txt"
(prinl "My 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.
| #Pike | Pike | Stdio.write_file("file.txt", "My 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.
| #PowerShell | PowerShell |
Get-Process | Out-File -FilePath .\ProcessList.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.
| #BBC_BASIC | BBC BASIC | PROCdrawAntiAliasedLine(100, 100, 600, 400, 0, 0, 0)
END
DEF PROCdrawAntiAliasedLine(x1, y1, x2, y2, r%, g%, b%)
LOCAL dx, dy, xend, yend, grad, yf, xgap, ix1%, iy1%, ix2%, iy2%, x%
dx = x2 - x1
dy = y2 - y1
IF ABS(dx) < ABS(dy) THEN
SWAP x1, y1
SWAP x2, y2
SWAP dx, dy
ENDIF
IF x2 < x1 THEN
SWAP x1, x2
SWAP y1, y2
ENDIF
grad = dy / dx
xend = INT(x1 + 0.5)
yend = y1 + grad * (xend - x1)
xgap = xend + 0.5 - x1
ix1% = xend
iy1% = INT(yend)
PROCplot(ix1%, iy1%, r%, b%, g%, (INT(yend) + 1 - yend) * xgap)
PROCplot(ix1%, iy1% + 1, r%, b%, g%, (yend - INT(yend)) * xgap)
yf = yend + grad
xend = INT(x2 + 0.5)
yend = y2 + grad * (xend - x2)
xgap = x2 + 0.5 - xend
ix2% = xend
iy2% = INT(yend)
PROCplot(ix2%, iy2%, r%, b%, g%, (INT(yend) + 1 - yend) * xgap)
PROCplot(ix2%, iy2% + 1, r%, b%, g%, (yend - INT(yend)) * xgap)
FOR x% = ix1% + 1 TO ix2% - 1
PROCplot(x%, INT(yf), r%, b%, g%, INT(yf) + 1 - yf)
PROCplot(x%, INT(yf) + 1, r%, b%, g%, yf - INT(yf))
yf += grad
NEXT
ENDPROC
DEF PROCplot(X%, Y%, R%, G%, B%, a)
LOCAL C%
C% = TINT(X%*2,Y%*2)
COLOUR 1, R%*a + (C% AND 255)*(1-a), \
\ G%*a + (C% >> 8 AND 255)*(1-a), \
\ B%*a + (C% >> 16 AND 255)*(1-a)
GCOL 1
LINE X%*2, Y%*2, X%*2, Y%*2
ENDPROC |
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 > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & 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.
| #AutoHotkey | AutoHotkey | gosub constants
names := xmlescape(names)
remarks := xmlescape(remarks)
stringsplit, remarks, remarks, `n
xml = "<CharacterRemarks>"
loop, parse, names, `n
xml .= "<Character name=" . A_LoopField . ">" . remarks%A_Index%
. "</Character>`n"
xml .= "</CharacterRemarks>"
msgbox % xml
return
xmlescape(string)
{
static
punc = ",>,<,<=,>=,',& ; "
xmlpunc = ",>,<,<=,>=,',&
if !punc1
{
StringSplit, punc, punc, `,
StringSplit, xmlpunc, xmlpunc, `,
}
escaped := string
loop, parse, punc, `,
{
StringReplace, escaped, escaped, % A_LoopField, % xmlpunc%A_Index%, All
}
Return escaped
}
constants:
#LTrim
names =
(
April
Tam O'Shanter
Emily
)
remarks =
(
Bubbly: I'm > Tam and <= Emily
Burns: "When chapman billies leave the street ..."
Short & shrift
)
return |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #AutoHotkey | AutoHotkey | students =
(
<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="Émily" />
</Students>
)
quote = " ; "
pos = 1
while, pos := RegExMatch(students, "Name=.(\w+)" . quote . "\sGender"
, name, pos + 1)
names .= name1 . "`n"
msgbox % 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)
| #Self | Self | vector copySize: 100 |
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.
| #Elena | Elena | import system'routines;
import extensions;
public singleton program
{
static games := new string[]{"12", "13", "14", "23", "24", "34"};
static results := "000000";
nextResult()
{
var s := results;
if (results=="222222") { ^ false };
results := (results.toInt(3) + 1).toString(3).padLeft($48, 6);
^ true
}
closure()
{
var points := IntMatrix.allocate(4, 10);
int counter := 0;
do
{
var records := new int[]{0,0,0,0};
for(int i := 0, i < 6, i += 1)
{
var r := results[i];
r =>
"2" { records[games[i][0].toInt() - 49] := records[games[i][0].toInt() - 49] + 3 }
"1" {
records[games[i][0].toInt() - 49] := records[games[i][0].toInt() - 49] + 1;
records[games[i][1].toInt() - 49] := records[games[i][1].toInt() - 49] + 1
}
"0" { records[games[i][1].toInt() - 49] := records[games[i][1].toInt() - 49] + 3 };
};
records := records.ascendant();
for(int i := 0, i <= 3, i += 1)
{
points[i][records[i]] := points[i][records[i]] + 1
}
}
while(program.nextResult());
new Range(0, 4).zipForEach(new string[]{"1st", "2nd", "3rd", "4th"}, (i,l)
{
console.printLine(l,": ", points[3 - i].toArray())
});
}
} |
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.
| #Elixir | Elixir | defmodule World_Cup do
def group_stage do
results = [[3,0],[1,1],[0,3]]
teams = [0,1,2,3]
allresults = combos(2,teams) |> combinations(results)
allpoints = for list <- allresults, do: (for {l1,l2} <- list, do: Enum.zip(l1,l2)) |> List.flatten
totalpoints = for list <- allpoints, do: (for t <- teams, do: {t, Enum.sum(for {t_,points} <- list, t_==t, do: points)} )
sortedtotalpoints = for list <- totalpoints, do: Enum.sort(list,fn({_,a},{_,b}) -> a > b end)
pointsposition = for n <- teams, do: (for list <- sortedtotalpoints, do: elem(Enum.at(list,n),1))
for n <- teams do
for points <- 0..9 do
Enum.at(pointsposition,n) |> Enum.filter(&(&1 == points)) |> length
end
end
end
defp combos(1, list), do: (for x <- list, do: [x])
defp combos(k, list) when k == length(list), do: [list]
defp combos(k, [h|t]) do
(for subcombos <- combos(k-1, t), do: [h | subcombos]) ++ (combos(k, t))
end
defp combinations([h],list2), do: (for item <- list2, do: [{h,item}])
defp combinations([h|t],list2) do
for item <- list2, comb <- combinations(t,list2), do: [{h,item} | comb]
end
end
format = String.duplicate("~4w", 10) <> "~n"
:io.format(format, Enum.to_list(0..9))
IO.puts String.duplicate(" ---", 10)
Enum.each(World_Cup.group_stage, fn x -> :io.format(format, x) 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.
| #Go | Go | package main
import (
"fmt"
"os"
)
var (
x = []float64{1, 2, 3, 1e11}
y = []float64{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}
xprecision = 3
yprecision = 5
)
func main() {
if len(x) != len(y) {
fmt.Println("x, y different length")
return
}
f, err := os.Create("filename")
if err != nil {
fmt.Println(err)
return
}
for i := range x {
fmt.Fprintf(f, "%.*e, %.*e\n", xprecision-1, x[i], yprecision-1, y[i])
}
f.Close()
} |
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.
| #M4 | M4 | define(`_set', `define(`$1[$2]', `$3')')dnl
define(`_get', `defn(`$1[$2]')')dnl
define(`for',`ifelse($#,0,``$0'',`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')dnl
define(`opposite',`_set(`door',$1,ifelse(_get(`door',$1),`closed',`open',`closed'))')dnl
define(`upper',`100')dnl
for(`x',`1',upper,`1',`_set(`door',x,`closed')')dnl
for(`x',`1',upper,`1',`for(`y',x,upper,x,`opposite(y)')')dnl
for(`x',`1',upper,`1',`door x is _get(`door',x)
')dnl |
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>
| #Lasso | Lasso |
content_type( 'text/xml' );// set MIME type if serving
xml( '<?xml version="1.0" ?><root><element>Some text here</element></root>' );
|
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>
| #Lingo | Lingo | -- create an XML document
doc = newObject("XML", "<?xml version='1.0' ?>")
root = doc.createElement("root")
doc.appendChild(root)
element = doc.createElement("element")
root.appendChild(element)
textNode = doc.createTextNode("Some text here")
element.appendChild(textNode)
put doc.toString()
-- "<?xml version='1.0' ?><root><element>Some text here</element></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
| #Arturo | Arturo | print {:
______ __
/\ _ \ /\ \__
\ \ \L\ \ _ __\ \ ,_\ __ __ _ __ ___
\ \ __ \/\`'__\ \ \/ /\ \/\ \/\`'__\/ __`\
\ \ \/\ \ \ \/ \ \ \_\ \ \_\ \ \ \//\ \L\ \
\ \_\ \_\ \_\ \ \__\\ \____/\ \_\\ \____/
\/_/\/_/\/_/ \/__/ \/___/ \/_/ \/___/
:} |
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.
| #PureBasic | PureBasic |
EnableExplicit
Define fOutput$ = "output.txt" ; enter path of file to create or overwrite
Define str$ = "This string is to be written to the file"
If OpenConsole()
If CreateFile(0, fOutput$)
WriteString(0, str$)
CloseFile(0)
Else
PrintN("Error creating or opening output file")
EndIf
PrintN("Press any key to close the console")
Repeat: Delay(10) : Until Inkey() <> ""
CloseConsole()
EndIf
|
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.
| #Python | Python | with open(filename, 'w') as f:
f.write(data) |
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.
| #Racket | Racket | #lang racket/base
(with-output-to-file "/tmp/out-file.txt" #:exists 'replace
(lambda () (display "characters"))) |
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
| #11l | 11l | V dict_fname = ‘unixdict.txt’
F load_dictionary(String fname = dict_fname)
‘Return appropriate words from a dictionary file’
R Set(File(fname).read().split("\n").filter(word -> re:‘[a-z]{3,}’.match(word)))
F get_players()
V names = input(‘Space separated list of contestants: ’)
R names.trim(‘ ’).split(‘ ’, group_delimiters' 1B).map(n -> n.capitalize())
F is_wordiff_removal(word, String prev; comment = 1B)
‘Is word derived from prev by removing one letter?’
V ans = word C Set((0 .< prev.len).map(i -> @prev[0 .< i]‘’@prev[i + 1 ..]))
I !ans
I comment
print(‘Word is not derived from previous by removal of one letter.’)
R ans
F counter(s)
DefaultDict[Char, Int] d
L(c) s
d[c]++
R d
F is_wordiff_insertion(String word, prev; comment = 1B) -> Bool
‘Is word derived from prev by adding one letter?’
V diff = counter(word)
L(c) prev
I --diff[c] <= 0
diff.pop(c)
V diffcount = sum(diff.values())
I diffcount != 1
I comment
print(‘More than one character insertion difference.’)
R 0B
V insert = Array(diff.keys())[0]
V ans = word C Set((0 .. prev.len).map(i -> @prev[0 .< i]‘’@insert‘’@prev[i ..]))
I !ans
I comment
print(‘Word is not derived from previous by insertion of one letter.’)
R ans
F is_wordiff_change(String word, String prev; comment = 1B) -> Bool
‘Is word derived from prev by changing exactly one letter?’
V diffcount = sum(zip(word, prev).map((w, p) -> Int(w != p)))
I diffcount != 1
I comment
print(‘More or less than exactly one character changed.’)
R 0B
R 1B
F is_wordiff(wordiffs, word, dic, comment = 1B)
‘Is word a valid wordiff from wordiffs[-1] ?’
I word !C dic
I comment
print(‘That word is not in my dictionary’)
R 0B
I word C wordiffs
I comment
print(‘That word was already used.’)
R 0B
I word.len < wordiffs.last.len
R is_wordiff_removal(word, wordiffs.last, comment)
E I word.len > wordiffs.last.len
R is_wordiff_insertion(word, wordiffs.last, comment)
R is_wordiff_change(word, wordiffs.last, comment)
F could_have_got(wordiffs, dic)
R (dic - Set(wordiffs)).filter(word -> is_wordiff(@wordiffs, word, @dic, comment' 0B))
V dic = load_dictionary()
V dic_3_4 = dic.filter(word -> word.len C (3, 4))
V start = random:choice(dic_3_4)
V wordiffs = [start]
V players = get_players()
V cur_player = 0
L
V name = players[cur_player]
cur_player = (cur_player + 1) % players.len
V word = input(name‘: Input a wordiff from '’wordiffs.last‘': ’).trim(‘ ’)
I is_wordiff(wordiffs, word, dic)
wordiffs.append(word)
E
print(‘YOU HAVE LOST ’name‘!’)
print(‘Could have used: ’(could_have_got(wordiffs, dic)[0.<10]).join(‘, ’)‘ ...’)
L.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.
| #C | C | void draw_line_antialias(
image img,
unsigned int x0, unsigned int y0,
unsigned int x1, unsigned int y1,
color_component r,
color_component g,
color_component b ); |
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 > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & 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.
| #BASIC | BASIC | 100 Q$ = CHR$(34)
110 DE$(0) = "April"
120 RE$(0) = "Bubbly: I'm > Tam and <= Emily"
130 DE$(1) = "Tam O'Shanter"
140 RE$(1) = "Burns: " + Q$ + "When chapman billies leave the street ..." + Q$
150 DE$(2) = "Emily"
160 RE$(2) = "Short & shrift"
200 Print "<CharacterRemarks>"
210 For I = 0 to 2
220 Print " <Character name="Q$;
230 X$=DE$(I) : GOSUB 300xmlquote
240 PRINT Q$">";
250 X$=RE$(I) : GOSUB 300xmlquote
260 PRINT "</Character>"
270 Next
280 Print "</CharacterRemarks>"
290 End
300 For n = 1 To Len(X$)
310 c$ = Mid$(X$,n,1)
320 IF C$ = "<" THEN C$ = "<"
330 IF C$ = ">" THEN C$ = ">"
340 IF C$ = "&" THEN C$ = "&"
350 IF C$ = Q$ THEN C$ = """
360 IF C$ = "'" THEN C$ = "'"
370 PRINT C$;
380 NEXT N
390 RETURN |
http://rosettacode.org/wiki/XML/Input | XML/Input | Given the following XML fragment, extract the list of student names using whatever means desired. If the only viable method is to use XPath, refer the reader to the task XML and XPath.
<Students>
<Student Name="April" Gender="F" DateOfBirth="1989-01-02" />
<Student Name="Bob" Gender="M" DateOfBirth="1990-03-04" />
<Student Name="Chad" Gender="M" DateOfBirth="1991-05-06" />
<Student Name="Dave" Gender="M" DateOfBirth="1992-07-08">
<Pet Type="dog" Name="Rover" />
</Student>
<Student DateOfBirth="1993-09-10" Gender="F" Name="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #AWK | AWK | function parse_buf()
{
if ( match(buffer, /<Student[ \t]+[^>]*Name[ \t]*=[ \t]*"([^"]*)"/, mt) != 0 ) {
students[mt[1]] = 1
}
buffer = ""
}
BEGIN {
FS=""
mode = 0
buffer = ""
li = 1
}
mode==1 {
for(i=1; i <= NF; i++) {
buffer = buffer $i
if ( $i == ">" ) {
mode = 0;
break;
}
}
if ( mode == 0 ) {
li = i
} else {
li = 1
}
# let us process the buffer if "complete"
if ( mode == 0 ) {
parse_buf()
}
}
mode==0 {
for(i=li; i <= NF; i++) {
if ( $i == "<" ) {
mode = 1
break;
}
}
for(j=i; i <= NF; i++) {
buffer = buffer $i
if ( $i == ">" ) {
mode = 0
parse_buf()
}
}
li = 1
}
END {
for(k in students) {
print k
}
} |
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)
| #SenseTalk | SenseTalk | // Initial creation of an array
set a to (1, 2, 3)
// pushing a value to the array
// Both approaches are valid
insert 4 after a
push 5 into a
put a -- (1, 2, 3, 4, 5)
// Treating the array as a stack, using `push` and `pop`
pop a into v1
put a -- (1, 2, 3, 4)
put v1-- 5
// Treating the array as a queue, using `push` and `pull`
push 6 into a
pull a into v2
put a -- (2, 3, 4, 6)
put v2 -- 1
// Referencing the items in the array
put the second item of a -- 3
// Changing the values in the array
set the third item of a to "abc"
put a -- (2, 3, "abc", 6) |
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.
| #Erlang | Erlang |
-module(world_cup).
-export([group_stage/0]).
group_stage() ->
Results = [[3,0],[1,1],[0,3]],
Teams = [1,2,3,4],
Matches = combos(2,Teams),
AllResults =
combinations(Matches,Results),
AllPoints =
[lists:flatten([lists:zip(L1,L2) || {L1,L2} <- L]) || L <- AllResults],
TotalPoints =
[ [ {T,lists:sum([Points || {T_,Points} <- L, T_ == T])} || T <- Teams] || L <- AllPoints],
SortedTotalPoints =
[ lists:sort(fun({_,A},{_,B}) -> A > B end,L) || L <- TotalPoints],
PointsPosition =
[ [element(2,lists:nth(N, L))|| L <- SortedTotalPoints ] || N <- Teams],
[ [length(lists:filter(fun(Points_) -> Points_ == Points end,lists:nth(N, PointsPosition) ))
|| Points <- lists:seq(0,9)] || N <- Teams].
combos(1, L) ->
[[X] || X <- L];
combos(K, L) when K == length(L) ->
[L];
combos(K, [H|T]) ->
[[H | Subcombos] || Subcombos <- combos(K-1, T)]
++ (combos(K, T)).
combinations([H],List2) ->
[[{H,Item}] || Item <- List2];
combinations([H|T],List2) ->
[ [{H,Item} | Comb] || Item <- List2, Comb <- combinations(T,List2)].
|
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.
| #Haskell | Haskell | import System.IO
import Text.Printf
import Control.Monad
writeDat filename x y xprec yprec =
withFile filename WriteMode $ \h ->
-- Haskell's printf doesn't support a precision given as an argument for some reason, so we insert it into the format manually:
let writeLine = hPrintf h $ "%." ++ show xprec ++ "g\t%." ++ show yprec ++ "g\n" in
zipWithM_ writeLine x y |
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.
| #HicEst | HicEst | REAL :: n=4, x(n), y(n)
CHARACTER :: outP = "Test.txt"
OPEN(FIle = outP)
x = (1, 2, 3, 1E11)
y = x ^ 0.5
DO i = 1, n
WRITE(FIle=outP, Format='F5, F10.3') x(i), y(i)
ENDDO |
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.
| #MAD | MAD | NORMAL MODE IS INTEGER
DIMENSION OPEN(100)
PRINT COMMENT $ $
R MAKE SURE ALL DOORS ARE CLOSED AT BEGINNING
THROUGH CLOSE, FOR DOOR=1, 1, DOOR.G.100
CLOSE OPEN(DOOR) = 0
R MAKE 100 PASSES
THROUGH TOGGLE, FOR PASS=1, 1, PASS.G.100
THROUGH TOGGLE, FOR DOOR=PASS, PASS, DOOR.G.100
TOGGLE OPEN(DOOR) = 1 - OPEN(DOOR)
R PRINT THE DOORS THAT ARE OPEN
THROUGH SHOW, FOR DOOR=1, 1, DOOR.G.100
SHOW WHENEVER OPEN(DOOR).E.1, PRINT FORMAT ISOPEN, DOOR
VECTOR VALUES ISOPEN = $5HDOOR ,I3,S1,8HIS OPEN.*$
END OF PROGRAM |
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>
| #Lua | Lua | require("LuaXML")
local dom = xml.new("root")
local element = xml.new("element")
table.insert(element, "Some text here")
dom:append(element)
dom:save("dom.xml") |
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>
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | DOM = XMLObject["Document"][{XMLObject["Declaration"]["Version" -> "1.0","Encoding" -> "utf-8"]},
XMLElement["root", {}, {XMLElement["element", {}, {"Some text here"}]}], {}];
ExportString[DOM, "XML", "AttributeQuoting" -> "\""] |
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
| #AutoHotkey | AutoHotkey | AutoTrim, Off
draw =
(
______ __ __ __ __
/\ __ \/\ \_\ \/\ \/ /
\ \ __ \ \ __ \ \ _"-.
\ \_\ \_\ \_\ \_\ \_\ \_\
\/_/\/_/\/_/\/_/\/_/\/_/
)
Gui, +ToolWindow
Gui, Color, 1A1A1A, 1A1A1A
Gui, Font, s8 cLime w800, Courier New
Gui, Add, text, x4 y0 , % " " draw
Gui, Show, w192 h82, AHK in 3D
return
GuiClose:
ExitApp |
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.
| #Raku | Raku | spurt 'path/to/file', $file-data; |
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.
| #RATFOR | RATFOR |
# Program to overwrite an existing file
open(11,FILE="file.txt")
101 format(A)
write(11,101) "Hello World"
close(11)
end
|
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.
| #REXX | REXX |
/*REXX*/
of='file.txt'
'erase' of
s=copies('1234567890',10000)
Call charout of,s
Call lineout of
Say chars(of) length(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 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
| #Arturo | Arturo | wordset: map read.lines relative "unixdict.txt" => strip
validAnswer?: function [answer][
if not? contains? wordset answer [
prints "\tNot a valid dictionary word."
return false
]
if contains? pastWords answer [
prints "\tWord already used."
return false
]
if 1 <> levenshtein answer last pastWords [
prints "\tNot a correct wordiff."
return false
]
return true
]
playerA: input "player A: what is your name? "
playerB: input "player B: what is your name? "
pastWords: new @[sample select wordset 'word [ contains? [3 4] size word ]]
print ["\nThe initial word is:" last pastWords "\n"]
current: playerA
while ø [
neww: strip input ~"|current|, what is the next word? "
while [not? validAnswer? neww][
neww: strip input " Try again: "
]
'pastWords ++ neww
current: (current=playerA)? -> playerB -> playerA
print ""
] |
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.2B.2B | C++ |
#include <functional>
#include <algorithm>
#include <utility>
void WuDrawLine(float x0, float y0, float x1, float y1,
const std::function<void(int x, int y, float brightess)>& plot) {
auto ipart = [](float x) -> int {return int(std::floor(x));};
auto round = [](float x) -> float {return std::round(x);};
auto fpart = [](float x) -> float {return x - std::floor(x);};
auto rfpart = [=](float x) -> float {return 1 - fpart(x);};
const bool steep = abs(y1 - y0) > abs(x1 - x0);
if (steep) {
std::swap(x0,y0);
std::swap(x1,y1);
}
if (x0 > x1) {
std::swap(x0,x1);
std::swap(y0,y1);
}
const float dx = x1 - x0;
const float dy = y1 - y0;
const float gradient = (dx == 0) ? 1 : dy/dx;
int xpx11;
float intery;
{
const float xend = round(x0);
const float yend = y0 + gradient * (xend - x0);
const float xgap = rfpart(x0 + 0.5);
xpx11 = int(xend);
const int ypx11 = ipart(yend);
if (steep) {
plot(ypx11, xpx11, rfpart(yend) * xgap);
plot(ypx11 + 1, xpx11, fpart(yend) * xgap);
} else {
plot(xpx11, ypx11, rfpart(yend) * xgap);
plot(xpx11, ypx11 + 1, fpart(yend) * xgap);
}
intery = yend + gradient;
}
int xpx12;
{
const float xend = round(x1);
const float yend = y1 + gradient * (xend - x1);
const float xgap = rfpart(x1 + 0.5);
xpx12 = int(xend);
const int ypx12 = ipart(yend);
if (steep) {
plot(ypx12, xpx12, rfpart(yend) * xgap);
plot(ypx12 + 1, xpx12, fpart(yend) * xgap);
} else {
plot(xpx12, ypx12, rfpart(yend) * xgap);
plot(xpx12, ypx12 + 1, fpart(yend) * xgap);
}
}
if (steep) {
for (int x = xpx11 + 1; x < xpx12; x++) {
plot(ipart(intery), x, rfpart(intery));
plot(ipart(intery) + 1, x, fpart(intery));
intery += gradient;
}
} else {
for (int x = xpx11 + 1; x < xpx12; x++) {
plot(x, ipart(intery), rfpart(intery));
plot(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 > Tam and <= Emily</Character>
<Character name="Tam O'Shanter">Burns: "When chapman billies leave the street ..."</Character>
<Character name="Emily">Short & 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.
| #Bracmat | Bracmat | ( ( 2XML
= PCDATAentities attributeValueEntities doAll doAttributes
, xml
. ( attributeValueEntities
= a c
. @( !arg
: ?a
(("<"|"&"|\"):?c)
?arg
)
& !a
"&"
( !c:"<"<
| !c:"&"&
| quot
)
";"
attributeValueEntities$!arg
| !arg
)
& ( PCDATAentities
= a c
. @( !arg
: ?a
(("<"|"&"|">"):?c)
?arg
)
& !a
"&"
( !c:"<"<
| !c:"&"&
| gt
)
";"
PCDATAentities$!arg
| !arg
)
& ( doAttributes
= a v
. !arg:(?a.?v) ?arg
& " "
PCDATAentities$!a
"=\""
attributeValueEntities$!v
\"
doAttributes$!arg
|
)
& ( doAll
= xml first A B C att XML
. !arg:?xml
& :?XML
& whl
' ( !xml:%?first ?xml
& ( !first:(?A.?B)
& ( !B:(?att,?C)
& !XML
( !C:
& "<" !A doAttributes$!att " />\n"
| "<"
!A
doAttributes$!att
">"
doAll$!C
"</"
!A
">\n"
)
: ?XML
| !A
: ( "!"&!XML "<!" !B ">":?XML
| "!--"
& !XML "<!--" !B "-->":?XML
| "?"&!XML "<?" !B "?>\n":?XML
| "![CDATA["
& !XML "<![CDATA[" !B "]]>":?XML
| "!DOCTYPE"
& !XML "<!DOCTYPE" !B ">":?XML
| ?
& !XML "<" !A doAttributes$!B ">":?XML
)
)
| !XML PCDATAentities$!first:?XML
)
)
& str$!XML
)
& doAll$!arg
)
& ( makeList
= characters name names remark remarks
. !arg:(?names.?remarks)
& :?characters
& whl
' ( (!names.!remarks)
: (%?name ?names.%?remark ?remarks)
& !characters (Character.(name.!name),!remark)
: ?characters
)
& ("?".xml) (CharacterRemarks.,!characters)
)
& put
$ ( 2XML
$ ( makeList
$ ( April "Tam O'Shanter" Emily
. "Bubbly: I'm > Tam and <= Emily"
"Burns: \"When chapman billies leave the street ...\""
"Short & shrift"
)
)
)
) |
http://rosettacode.org/wiki/XML/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="Émily" />
</Students>
Expected Output
April
Bob
Chad
Dave
Émily
| #BBC_BASIC | BBC BASIC | INSTALL @lib$+"XMLLIB"
xmlfile$ = "C:\students.xml"
PROC_initXML(xmlobj{}, xmlfile$)
level% = FN_skipTo(xmlobj{}, "Students", 0)
IF level%=0 ERROR 100, "Students not found"
REPEAT
IF FN_isTag(xmlobj{}) THEN
tag$ = FN_nextToken(xmlobj{})
IF LEFT$(tag$, 8) = "<Student" THEN
np% = INSTR(tag$, "Name")
IF np% THEN PRINT FN_repEnt(EVAL(MID$(tag$, np%+5)))
ENDIF
ELSE
dummy$ = FN_nextToken(xmlobj{})
ENDIF
UNTIL FN_getLevel(xmlobj{}) < level%
PROC_exitXML(xmlobj{}) |
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)
| #Sidef | Sidef | # create an empty array
var arr = [];
# push objects into the array
arr << "a"; #: ['a']
arr.append(1,2,3); #: ['a', 1, 2, 3]
# change an element inside the array
arr[2] = "b"; #: ['a', 1, 'b', 3]
# set the value at a specific index in the array (with autovivification)
arr[5] = "end"; #: ['a', 1, 'b', 3, nil, 'end']
# resize the array
arr.resize_to(-1); #: []
# slice assignment
arr[0..2] = @|('a'..'c'); #: ['a', 'b', 'c']
# indices as arrays
var indices = [0, -1];
arr[indices] = ("foo", "baz"); #: ['foo', 'b', 'baz']
# retrieve multiple elements
var *elems = arr[0, -1]
say elems #=> ['foo', 'baz']
# retrieve an element
say arr[-1]; #=> 'baz' |
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.
| #Go | Go | package main
import (
"fmt"
"sort"
"strconv"
)
var games = [6]string{"12", "13", "14", "23", "24", "34"}
var results = "000000"
func nextResult() bool {
if results == "222222" {
return false
}
res, _ := strconv.ParseUint(results, 3, 32)
results = fmt.Sprintf("%06s", strconv.FormatUint(res+1, 3))
return true
}
func main() {
var points [4][10]int
for {
var records [4]int
for i := 0; i < len(games); i++ {
switch results[i] {
case '2':
records[games[i][0]-'1'] += 3
case '1':
records[games[i][0]-'1']++
records[games[i][1]-'1']++
case '0':
records[games[i][1]-'1'] += 3
}
}
sort.Ints(records[:])
for i := 0; i < 4; i++ {
points[i][records[i]]++
}
if !nextResult() {
break
}
}
fmt.Println("POINTS 0 1 2 3 4 5 6 7 8 9")
fmt.Println("-------------------------------------------------------------")
places := [4]string{"1st", "2nd", "3rd", "4th"}
for i := 0; i < 4; i++ {
fmt.Print(places[i], " place ")
for j := 0; j < 10; j++ {
fmt.Printf("%-5d", points[3-i][j])
}
fmt.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.
| #Icon_and_Unicon | Icon and Unicon | link printf
procedure main()
every put(x := [], (1 to 3) | 1e11)
every put(y := [], sqrt(!x))
every fprintf(open("filename","w"),"%10.2e %10.4e\n", x[i := 1 to *x], y[i])
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.
| #IDL | IDL | ; the data:
x = [1,2,3,1e11]
y=sqrt(x)
xprecision=3
yprecision=5
; NOT how one would do things in IDL, but in the spirit of the task - the output format:
form = string(xprecision,yprecision,format='("(G0.",I0.0,",1x,G0.",I0.0,")")')
; file I/O:
openw,unit,"datafile.txt",/get
for i = 1L, n_elements(x) do printf, unit, x[i-1],y[i-1],format=form
free_lun,unit
|
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.
| #Maple | Maple |
NDoors := proc( N :: posint )
# Initialise, using 0 to represent "closed"
local pass, door, doors := Array( 1 .. N, 'datatype' = 'integer'[ 1 ] );
# Now do N passes
for pass from 1 to N do
for door from pass by pass while door <= N do
doors[ door ] := 1 - doors[ door ]
end do
end do;
# Output
for door from 1 to N do
printf( "Door %d is %s.\n", door, `if`( doors[ door ] = 0, "closed", "open" ) )
end do;
# Since this is a printing routine, return nothing.
NULL
end proc:
|
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>
| #MATLAB | MATLAB | docNode = com.mathworks.xml.XMLUtils.createDocument('root');
docRootNode = docNode.getDocumentElement;
thisElement = docNode.createElement('element');
thisElement.appendChild(docNode.createTextNode('Some text here'));
docRootNode.appendChild(thisElement);
|
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>
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
import java.io.StringWriter
import javax.xml.
import org.w3c.dom.
class RDOMSerialization public
properties private
domDoc = Document
method main(args = String[]) public static
lcl = RDOMSerialization()
lcl.buildDOMDocument()
lcl.serializeXML()
return
method buildDOMDocument() inheritable
do
factory = DocumentBuilderFactory.newInstance()
builder = factory.newDocumentBuilder()
impl = builder.getDOMImplementation()
domDoc = impl.createDocument(null, null, null)
elmt1 = domDoc.createElement("root")
elmt2 = domDoc.createElement("element")
elmt2.setTextContent("Some text here")
domDoc.appendChild(elmt1)
elmt1.appendChild(elmt2)
catch exPC = ParserConfigurationException
exPC.printStackTrace
end
return
method serializeXML() inheritable
do
domSrc = DOMSource(domDoc)
txformer = TransformerFactory.newInstance().newTransformer()
txformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no")
txformer.setOutputProperty(OutputKeys.METHOD, "xml")
txformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8")
txformer.setOutputProperty(OutputKeys.INDENT, "yes")
txformer.setOutputProperty(OutputKeys.STANDALONE, "yes")
txformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2")
sw = StringWriter()
sr = StreamResult(sw)
txformer.transform(domSrc, sr)
say sw.toString
catch exTC = TransformerConfigurationException
exTC.printStackTrace
catch exTF = TransformerFactoryConfigurationError
exTF.printStackTrace
catch exTE = TransformerException
exTE.printStackTrace
end
return
|
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
| #AWK | AWK |
# syntax: GAWK -f WRITE_LANGUAGE_NAME_IN_3D_ASCII.AWK
BEGIN {
arr[1] = " xxxx x x x x"
arr[2] = "x x x x x x"
arr[3] = "x x x x x x"
arr[4] = "xxxxxx x x xx"
arr[5] = "x x x xx x xx"
arr[6] = "x x xx xx x x"
arr[7] = "x x xx xx x x"
arr[8] = "A V P J B W"
for (i=1; i<=8; i++) {
x = arr[i]
gsub(/./,"& ",x)
gsub(/[xA-Z] /,"_/",x)
print(x)
}
exit(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.
| #Ring | Ring |
write("myfile.txt","Hello, World!")
|
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.
| #Ruby | Ruby | open(fname, 'w'){|f| f.write(str) } |
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.
| #Rust | Rust | use std::fs::File;
use std::io::Write;
fn main() -> std::io::Result<()> {
let data = "Sample text.";
let mut file = File::create("filename.txt")?;
write!(file, "{}", data)?;
Ok(())
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.