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.
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
%n 100 !n
0 $n repeat
$n [dup sqrt int dup * over
== ( [1 swap set] [drop] ) if] for
$n [ ( "The door " over " is " ) lprint get ( ["OPEN"] ["closed"] ) if print nl] for
( "Time elapsed: " msec " seconds" ) lprint nl
pstack
" " input |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Scala | Scala | object RegisterWinLogEvent extends App {
import sys.process._
def eventCreate= Seq("EVENTCREATE", "/T", "SUCCESS", "/id", "123", "/l", "APPLICATION", "/so", "Scala RegisterWinLogEvent", "/d", "Rosetta Code Example" ).!!
println(eventCreate)
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
} |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Standard_ML | Standard ML |
OS.Process.system "logger \"Log event\" " ;
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Tcl | Tcl | package require twapi
# This command handles everything; use “-type error” to write an error message
twapi::eventlog_log "My Test Event" -type info |
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.
| #AutoHotkey | AutoHotkey | file := FileOpen("test.txt", "w")
file.Write("this is a test string")
file.Close() |
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.
| #AWK | AWK |
# syntax: GAWK -f WRITE_ENTIRE_FILE.AWK
BEGIN {
dev = "FILENAME.TXT"
print("(Over)write a file so that it contains a string.") >dev
close(dev)
exit(0)
}
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Red | Red | arr1: [] ;create empty array
arr2: ["apple" "orange" 1 2 3] ;create an array with data
>> insert arr1 "blue"
>> arr1
== ["blue"]
append append arr1 "black" "green"
>> arr1
== ["blue" "black" "green"]
>> arr1/2
== "black"
>> second arr1
== "black"
>> pick arr1 2
== "black" |
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.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
procedure Write_Float_Array is
type Float_Array is array (1..4) of Float;
procedure Write_Columns
( File : File_Type;
X : Float_Array;
Y : Float_Array;
X_Pres : Natural := 3;
Y_Pres : Natural := 5
) is
begin
for I in Float_Array'range loop
Put (File => File, Item => X(I), Fore => 1, Aft => X_Pres - 1);
Put (File, " ");
Put (File => File, Item => Y(I), Fore => 1, Aft => Y_Pres - 1);
New_Line (File);
end loop;
end Write_Columns;
File : File_Type;
X : Float_Array := (1.0, 2.0, 3.0, 1.0e11);
Y : Float_Array;
begin
Put ("Tell us the file name to write:");
Create (File, Out_File, Get_Line);
for I in Float_Array'range loop
Y(I) := Sqrt (X (I));
end loop;
Write_columns (File, X, Y);
Close (File);
end Write_Float_Array; |
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.
| #Klong | Klong |
flip::{,/{(1-*x),1_x}'x:#y}
i::0;(100{i::i+1;flip(i;x)}:*100:^0)?1
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #VBScript | VBScript |
Sub write_event(event_type,msg)
Set objShell = CreateObject("WScript.Shell")
Select Case event_type
Case "SUCCESS"
n = 0
Case "ERROR"
n = 1
Case "WARNING"
n = 2
Case "INFORMATION"
n = 4
Case "AUDIT_SUCCESS"
n = 8
Case "AUDIT_FAILURE"
n = 16
End Select
objShell.LogEvent n, msg
Set objShell = Nothing
End Sub
Call write_event("INFORMATION","This is a test information.")
|
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #Wren | Wren | /* write_to_windows_event_log.wren */
class Windows {
foreign static eventCreate(args)
}
var args = [
"/T", "INFORMATION", "/ID", "123", "/L", "APPLICATION",
"/SO", "Wren", "/D", "\"Rosetta Code Example\""
].join(" ")
Windows.eventCreate(args) |
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.
| #BaCon | BaCon | SAVE s$ TO filename$ |
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.
| #BASIC | BASIC | f = freefile
open f, "output.txt"
write f, "This string is to be written to the file"
close f |
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.
| #BBC_BASIC | BBC BASIC | file% = OPENOUT filename$
PRINT#file%, text$
CLOSE#file% |
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)
| #ReScript | ReScript | let arr = [1, 2, 3]
let _ = Js.Array2.push(arr, 4)
arr[3] = 5
Js.log(Js.Int.toString(arr[3])) |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #ALGOL_68 | ALGOL 68 | PROC writedat = (STRING filename, []REAL x, y, INT x width, y width)VOID: (
FILE f;
INT errno = open(f, filename, stand out channel);
IF errno NE 0 THEN stop FI;
FOR i TO UPB x DO
# FORMAT := IF the absolute exponent is small enough, THEN use fixed ELSE use float FI; #
FORMAT repr x := ( ABS log(x[i])<x width | $g(-x width,x width-2)$ | $g(-x width,x width-4,-1)$ ),
repr y := ( ABS log(y[i])<y width | $g(-y width,y width-2)$ | $g(-y width,y width-4,-1)$ );
putf(f, (repr x, x[i], $" "$, repr y, y[i], $l$))
OD;
close(f)
);
# Example usage: #
test:(
[]REAL x = (1, 2, 3, 1e11);
[UPB x]REAL y; FOR i TO UPB x DO y[i]:=sqrt(x[i]) OD;
printf(($"x before:"$, $xg$, x, $l$));
printf(($"y before:"$, $xg$, y, $l$));
writedat("sqrt.dat", x, y, 3+2, 5+2);
printf($"After:"l$);
FILE sqrt dat;
INT errno = open(sqrt dat, "sqrt.dat", stand in channel);
IF errno NE 0 THEN stop FI;
on logical file end(sqrt dat, (REF FILE sqrt dat)BOOL: stop);
TO UPB x DO
STRING line;
get(sqrt dat, (line, new line));
print((line,new line))
OD
) |
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.
| #Kotlin | Kotlin | fun oneHundredDoors(): List<Int> {
val doors = BooleanArray(100, { false })
for (i in 0..99) {
for (j in i..99 step (i + 1)) {
doors[j] = !doors[j]
}
}
return doors
.mapIndexed { i, b -> i to b }
.filter { it.second }
.map { it.first + 1 }
} |
http://rosettacode.org/wiki/Write_to_Windows_event_log | Write to Windows event log | Task
Write script status to the Windows Event Log
| #zkl | zkl | zkl: System.cmd(0'|eventcreate "/T" "INFORMATION" "/ID" "123" "/D" "Rosetta Code example"|) |
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>
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program createXml64.s */
/* install package libxml++2.6-dev */
/* link with gcc option -I/usr/include/libxml2 -lxml2 */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEndpgm: .asciz "Normal end of program.\n"
szFileName: .asciz "file1.xml"
szFileMode: .asciz "w"
szMessError: .asciz "Error detected !!!!. \n"
szVersDoc: .asciz "1.0"
szLibRoot: .asciz "root"
szLibElement: .asciz "element"
szText: .asciz "some text here"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszVersDoc
bl xmlNewDoc // create doc
mov x19,x0 // doc address
mov x0,#0
ldr x1,qAdrszLibRoot
bl xmlNewNode // create root node
cbz x0,99f
mov x20,x0 // node root address
mov x0,x19
mov x1,x20
bl xmlDocSetRootElement
mov x0,#0
ldr x1,qAdrszLibElement
bl xmlNewNode // create element node
mov x21,x0 // node element address
ldr x0,qAdrszText
bl xmlNewText // create text
mov x22,x0 // text address
mov x0,x21 // node element address
mov x1,x22 // text address
bl xmlAddChild // add text to element node
mov x0,x20 // node root address
mov x1,x21 // node element address
bl xmlAddChild // add node elemeny to root node
ldr x0,qAdrszFileName
ldr x1,qAdrszFileMode
bl fopen // file open
cmp x0,#0
blt 99f
mov x23,x0 // File descriptor
mov x1,x19 // doc
mov x2,x20 // root
bl xmlElemDump // write xml file
cmp x0,#0
blt 99f
mov x0,x23
bl fclose // file close
mov x0,x19
bl xmlFreeDoc
bl xmlCleanupParser
ldr x0,qAdrszMessEndpgm
bl affichageMess
b 100f
99: // error
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessError: .quad szMessError
qAdrszMessEndpgm: .quad szMessEndpgm
qAdrszVersDoc: .quad szVersDoc
qAdrszLibRoot: .quad szLibRoot
qAdrszLibElement: .quad szLibElement
qAdrszText: .quad szText
qAdrszFileName: .quad szFileName
qAdrszFileMode: .quad szFileMode
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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.
| #Bracmat | Bracmat | put$("(Over)write a file so that it contains a string.",file,NEW) |
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.
| #C | C | /*
* Write Entire File -- RossetaCode -- dirty hackish solution
*/
#define _CRT_SECURE_NO_WARNINGS // turn off MS Visual Studio restrictions
#include <stdio.h>
int main(void)
{
return 0 >= fputs("ANY STRING TO WRITE TO A FILE AT ONCE.",
freopen("sample.txt","wb",stdout));
}
|
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.
| #C.23 | C# | System.IO.File.WriteAllText("filename.txt", "This file contains a string."); |
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)
| #Retro | Retro |
needs array'
( Create an array with four elements )
^array'new{ 1 2 3 4 } constant a
( Add 10 to each element in an array and update the array with the results )
a [ 10 + ] ^array'map
( Apply a quote to each element in an array; leaves the contents alone )
a [ 10 + putn cr ] ^array'apply
( Display an array )
a ^array'display
( Look for a value in an array )
3 a ^array'in?
6 a ^array'in?
( Look for a string in an array )
"hello" a ^array'stringIn?
( Reverse the order of items in an array )
a ^array'reverse
( Append two arrays and return a new one )
^array'new{ 1 2 3 } constant a
^array'new{ 4 5 6 } constant b
a b ^array'append constant c
( Create an array from the values returned by a quote )
[ 1 2 "hello" "world" ] ^array'fromQuote constant d
( Create a quote from the values in an array )
d ^array'toQuote
|
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.
| #Amazing_Hopper | Amazing Hopper |
#include <flow.h>
DEF-MAIN(argv,argc)
VOID( x ), MSET( y, f )
MEM(1,2,3,1.0e11), APND-LST(x), SET( y, x )
SET-ROUND(5), SQRT(y), MOVE-TO(y)
UNSET-ROUND
CAT-COLS( f, y, x )
TOK-SEP( TAB ), SAVE-MAT(f, "filename.txt" )
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.
| #AWK | AWK | $ awk 'BEGIN{split("1 2 3 1e11",x);
> split("1 1.4142135623730951 1.7320508075688772 316227.76601683791",y);
> for(i in x)printf("%6g %.5g\n",x[i],y[i])}'
1e+11 3.1623e+05
1 1
2 1.4142
3 1.7321 |
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.
| #KQL | KQL | range InitialDoor from 1 to 100 step 1
| extend DoorsVisited=range(InitialDoor, 100, InitialDoor)
| mvexpand DoorVisited=DoorsVisited to typeof(int)
| summarize VisitCount=count() by DoorVisited
| project Door=DoorVisited, IsOpen=(VisitCount % 2) == 1 |
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>
| #ABAP | ABAP |
DATA: xml_string TYPE string.
DATA(xml) = cl_ixml=>create( ).
DATA(doc) = xml->create_document( ).
DATA(root) = doc->create_simple_element( name = 'root'
parent = doc ).
doc->create_simple_element( name = 'element'
parent = root
value = 'Some text here' ).
DATA(stream_factory) = xml->create_stream_factory( ).
DATA(stream) = stream_factory->create_ostream_cstring( string = xml_string ).
DATA(renderer) = xml->create_renderer( document = doc
ostream = stream ).
stream->set_pretty_print( abap_true ).
renderer->render( ).
cl_demo_output=>display_text( xml_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.
| #C.2B.2B | C++ | #include <fstream>
using namespace std;
int main()
{
ofstream file("new.txt");
file << "this is a string";
file.close();
return 0;
} |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Clojure | Clojure | (spit "file.txt" "this is a string") |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #COBOL | COBOL |
IDENTIFICATION DIVISION.
PROGRAM-ID. Overwrite.
AUTHOR. Bill Gunshannon.
INSTALLATION. Home.
DATE-WRITTEN. 31 December 2021.
************************************************************
** Program Abstract:
** Simple COBOL task. Open file for output. Write
** data to file. Close file. Done...
************************************************************
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT File-Name ASSIGN TO "File.txt"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD File-Name
DATA RECORD IS Record-Name.
01 Record-Name.
02 Field1 PIC X(80).
WORKING-STORAGE SECTION.
01 New-Val PIC X(80)
VALUE 'Hello World'.
PROCEDURE DIVISION.
Main-Program.
OPEN OUTPUT File-Name.
WRITE Record-Name FROM New-Val.
CLOSE File-Name.
STOP RUN.
END-PROGRAM.
|
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)
| #REXX | REXX | /*REXX program demonstrates a simple array usage. */
a.='not found' /*value for all a.xxx (so far).*/
do j=1 to 100 /*start at 1, define 100 elements*/
a.j=-j*1000 /*define as negative J thousand. */
end /*j*/ /*the above defines 100 elements.*/
say 'element 50 is:' a.50
say 'element 3000 is:' a.3000
/*stick a fork in it, we're done.*/ |
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.
| #BASIC256 | BASIC256 | x$ = "1 2 3 1e11"
x$ = explode(x$, " ")
f = freefile
open f, "filename.txt"
for i = 0 to x$[?]-1
writeline f, int(x$[i]) + chr(9) + round(sqrt(x$[i]),4)
next i
close f |
http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file | Write float arrays to a text file | Task
Write two equal-sized numerical arrays 'x' and 'y' to
a two-column text file named 'filename'.
The first column of the file contains values from an 'x'-array with a
given 'xprecision', the second -- values from 'y'-array with 'yprecision'.
For example, considering:
x = {1, 2, 3, 1e11};
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791};
/* sqrt(x) */
xprecision = 3;
yprecision = 5;
The file should look like:
1 1
2 1.4142
3 1.7321
1e+011 3.1623e+005
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #BBC_BASIC | BBC BASIC | DIM x(3), y(3)
x() = 1, 2, 3, 1E11
FOR i% = 0 TO 3
y(i%) = SQR(x(i%))
NEXT
xprecision = 3
yprecision = 5
outfile% = OPENOUT("filename.txt")
IF outfile%=0 ERROR 100, "Could not create file"
FOR i% = 0 TO 3
@% = &1000000 + (xprecision << 8)
a$ = STR$(x(i%)) + CHR$(9)
@% = &1000000 + (yprecision << 8)
a$ += STR$(y(i%))
PRINT #outfile%, a$ : BPUT #outfile%, 10
NEXT
CLOSE #outfile% |
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.
| #LabVIEW | LabVIEW | var .doors = arr 100, false
for .i of .doors {
for .j = .i; .j <= len(.doors); .j += .i {
.doors[.j] = not .doors[.j]
}
}
writeln wherekeys .doors |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Ada | Ada | with Ada.Text_IO.Text_Streams;
with DOM.Core.Documents;
with DOM.Core.Nodes;
procedure Serialization is
My_Implementation : DOM.Core.DOM_Implementation;
My_Document : DOM.Core.Document;
My_Root_Node : DOM.Core.Element;
My_Element_Node : DOM.Core.Element;
My_Text_Node : DOM.Core.Text;
begin
My_Document := DOM.Core.Create_Document (My_Implementation);
My_Root_Node := DOM.Core.Documents.Create_Element (My_Document, "root");
My_Root_Node := DOM.Core.Nodes.Append_Child (My_Document, My_Root_Node);
My_Element_Node := DOM.Core.Documents.Create_Element (My_Document, "element");
My_Element_Node := DOM.Core.Nodes.Append_Child (My_Root_Node, My_Element_Node);
My_Text_Node := DOM.Core.Documents.Create_Text_Node (My_Document, "Some text here");
My_Text_Node := DOM.Core.Nodes.Append_Child (My_Element_Node, My_Text_Node);
DOM.Core.Nodes.Write
(Stream => Ada.Text_IO.Text_Streams.Stream
(Ada.Text_IO.Standard_Output),
N => My_Document,
Pretty_Print => True);
end Serialization; |
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>
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program createXml.s */
/* install package libxml++2.6-dev */
/* link with gcc option -lxml2 */
/* 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 "file1.xml"
szFileMode: .asciz "w"
szMessError: .asciz "Error detected !!!!. \n"
szVersDoc: .asciz "1.0"
szLibRoot: .asciz "root"
szLibElement: .asciz "element"
szText: .asciz "some text here"
szCarriageReturn: .asciz "\n"
/*********************************/
/* 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,iAdrszLibRoot
bl xmlNewNode @ create root node
mov r8,r0 @ node root address
mov r0,r9
mov r1,r8
bl xmlDocSetRootElement
@TODO voir la gestion des erreurs
mov r0,#0
ldr r1,iAdrszLibElement
bl xmlNewNode @ create element node
mov r7,r0 @ node element address
ldr r0,iAdrszText
bl xmlNewText @ create text
mov r6,r0 @ text address
mov r0,r7 @ node element address
mov r1,r6 @ text address
bl xmlAddChild @ add text to element node
mov r0,r8 @ node root address
mov r1,r7 @ node element address
bl xmlAddChild @ add node elemeny to root node
ldr r0,iAdrszFileName
ldr r1,iAdrszFileMode
bl fopen @ file open
cmp r0,#0
blt 99f
mov r5,r0 @ File descriptor
mov r1,r9 @ doc
mov r2,r8 @ root
bl xmlElemDump @ write xml file
cmp r0,#0
blt 99f
mov r0,r5
bl fclose @ file close
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
iAdrszLibRoot: .int szLibRoot
iAdrszLibElement: .int szLibElement
iAdrszText: .int szText
iAdrszFileName: .int szFileName
iAdrszFileMode: .int szFileMode
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* 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/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.
| #Common_Lisp | Common Lisp | (with-open-file (str "filename.txt"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(format str "File content...~%")) |
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.
| #D | D | import std.stdio;
void main() {
auto file = File("new.txt", "wb");
file.writeln("Hello World!");
} |
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)
| #Ring | Ring | # create an array with one string in it
a = ['foo']
# add items
a + 1 # ["foo", 1]
# set the value at a specific index in the array
a[1] = 2 # [2, 1]
# retrieve an element
see a[1] |
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.
| #C | C | #include <stdio.h>
#include <math.h>
int main(int argc, char **argv) {
float x[4] = {1,2,3,1e11}, y[4];
int i = 0;
FILE *filePtr;
filePtr = fopen("floatArray","w");
for (i = 0; i < 4; i++) {
y[i] = sqrt(x[i]);
fprintf(filePtr, "%.3g\t%.5g\n", x[i], y[i]);
}
return 0;
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #langur | langur | var .doors = arr 100, false
for .i of .doors {
for .j = .i; .j <= len(.doors); .j += .i {
.doors[.j] = not .doors[.j]
}
}
writeln wherekeys .doors |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #AutoHotkey | AutoHotkey | version = "1.0"
xmlheader := "<?xml version=" . version . "?>" . "<" . root . ">"
element("root", "child")
element("root", "element", "more text here")
element("root_child", "kid", "yak yak")
MsgBox % xmlheader . serialize("root")
Return
element(parent, name, text="")
{
Global
%parent%_children .= name . "`n"
%parent%_%name% = %parent%_%name%
%parent%_%name%_name := name
%parent%_%name%_text := text
}
serialize(root){
StringSplit, root, root, _
xml .= "<" . root%root0% . ">"
StringTrimRight, %root%_children, %root%_children, 1
Loop, Parse, %root%_children, `n
{
If %root%_%A_LoopField%_children
xml .= serialize(%root%_%A_LoopField%)
Else
{
element := "<" . %root%_%A_LoopField%_name . ">"
element .= %root%_%A_LoopField%_text
element .= "</" . %root%_%A_LoopField%_name . ">"
xml .= element
}
}
Return xml .= "</" . root%root0% . ">"
} |
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.
| #Delphi | Delphi |
program Write_entire_file;
{$APPTYPE CONSOLE}
uses
System.IoUtils;
begin
TFile.WriteAllText('filename.txt', 'This file contains a string.');
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.
| #Elena | Elena | import system'io;
public program()
{
File.assign("filename.txt").saveContent("This file contains a string.")
} |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Elixir | Elixir | File.write("file.txt", string) |
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)
| #RLaB | RLaB |
// 1-D (row- or column-vectors)
// Static:
// row-vector
x = [1:3];
x = zeros(1,3); x[1]=1; x[2]=2; x[3]=3;
// column-vector
x = [1:3]'; // or
x = [1;2;3]; // or
x = zeros(3,1); x[1]=1; x[2]=2; x[3]=3;
// Dynamic:
x = []; // create an empty array
x = [x; 1, 2]; // add a row to 'x' containing [1, 2], or
x = [x, [1; 2]]; // add a column to 'x' containing [1; 2]
// 2-D array
// Static:
x = zeros(3,5); // create an zero-filed matrix of size 3x5
x[1;1] = 1; // set the x(1,1) element to 1
x[2;] = [1,2,3,4,5]; // set the second row x(2,) to a row vector
x[3;4:5] = [2,3]; // set x(3,4) to 2 and x(3,5) to 3
// Dynamic
x = [1:5]; // create an row-vector x(1,1)=1, x(1,2)=2, ... x(1,5)=5
x = [x; 2, 3, 4, 6, 7]; // add to 'x' a row.
// Accessing an element of arrays:
// to retrieve/print element of matrix 'x' just put this in a single line in the script
i=1;
j=2;
x[i;j]
|
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.
| #C.23 | C# | using System.IO;
class Program
{
static void Main(string[] args)
{
var x = new double[] { 1, 2, 3, 1e11 };
var y = new double[] { 1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791 };
int xprecision = 3;
int yprecision = 5;
string formatString = "{0:G" + xprecision + "}\t{1:G" + yprecision + "}";
using (var outf = new StreamWriter("FloatArrayColumns.txt"))
for (int i = 0; i < x.Length; i++)
outf.WriteLine(formatString, x[i], y[i]);
}
} |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #lambdatalk | lambdatalk |
1) unoptimized version
{def doors
{A.new
{S.map {lambda {} false} {S.serie 1 100}}}}
-> doors
{def toggle
{lambda {:i :a}
{let { {_ {A.set! :i {not {A.get :i :a}} :a} }}}}}
-> toggle
{S.map {lambda {:b}
{S.map {lambda {:i} {toggle :i {doors}}}
{S.serie :b 99 {+ :b 1}}}}
{S.serie 0 99}}
->
{S.replace \s by space in
{S.map {lambda {:i} {if {A.get :i {doors}} then {+ :i 1} else}}
{S.serie 0 99}}}
-> 1 4 9 16 25 36 49 64 81 100
2.2) optimized version
{S.replace \s by space in
{S.map {lambda {:i}
{let { {:root {sqrt :i}} }
{if {= :root {round :root}}
then {* :root :root}
else}}}
{S.serie 1 100}}}
-> 1 4 9 16 25 36 49 64 81 100
|
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>
| #Bracmat | Bracmat | ( ("?"."xml version=\"1.0\" ")
\n
(root.,"\n " (element.,"
Some text here
") \n)
: ?xml
& out$(toML$!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>
| #C | C | #include <libxml/parser.h>
#include <libxml/tree.h>
int main()
{
xmlDoc *doc = xmlNewDoc("1.0");
xmlNode *root = xmlNewNode(NULL, BAD_CAST "root");
xmlDocSetRootElement(doc, root);
xmlNode *node = xmlNewNode(NULL, BAD_CAST "element");
xmlAddChild(node, xmlNewText(BAD_CAST "some text here"));
xmlAddChild(root, node);
xmlSaveFile("myfile.xml", doc);
xmlFreeDoc(doc);
xmlCleanupParser();
} |
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.
| #F.23 | F# | System.IO.File.WriteAllText("filename.txt", "This file contains a string.") |
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Factor | Factor | USING: io.encodings.utf8 io.files ;
"this is a string" "file.txt" utf8 set-file-contents |
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.
| #Fortran | Fortran | OPEN (F,FILE="SomeFileName.txt",STATUS="REPLACE")
WRITE (F,*) "Whatever you like."
WRITE (F) BIGARRAY |
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)
| #Robotic | Robotic |
set "index" to 0
. "Assign random values to array"
: "loop"
set "array&index&" to random 0 to 99
inc "index" by 1
if "index" < 100 then "loop"
* "Value of index 50 is ('array('50')')."
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.
| #C.2B.2B | C++ | template<class InputIterator, class InputIterator2>
void writedat(const char* filename,
InputIterator xbegin, InputIterator xend,
InputIterator2 ybegin, InputIterator2 yend,
int xprecision=3, int yprecision=5)
{
std::ofstream f;
f.exceptions(std::ofstream::failbit | std::ofstream::badbit);
f.open(filename);
for ( ; xbegin != xend and ybegin != yend; ++xbegin, ++ybegin)
f << std::setprecision(xprecision) << *xbegin << '\t'
<< std::setprecision(yprecision) << *ybegin << '\n';
} |
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.
| #Lasso | Lasso | loop(100) => {^
local(root = math_sqrt(loop_count))
local(state = (#root == math_ceil(#root) ? '<strong>open</strong>' | 'closed'))
#state != 'closed' ? 'Door ' + loop_count + ': ' + #state + '<br>'
^} |
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>
| #C.23 | C# | using System.Xml;
using System.Xml.Serialization;
[XmlRoot("root")]
public class ExampleXML
{
[XmlElement("element")]
public string element = "Some text here";
static void Main(string[] args)
{
var xmlnamespace = new XmlSerializerNamespaces();
xmlnamespace.Add("", ""); //used to stop default namespaces from printing
var writer = XmlWriter.Create("output.xml");
new XmlSerializer(typeof(ExampleXML)).Serialize(writer, new ExampleXML(), xmlnamespace);
}
//Output: <?xml version="1.0" encoding="utf-8"?><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>
| #C.2B.2B | C++ |
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlerror.h>
#include <libxml/xmlsave.h>
#include <libxml/xmlstring.h>
#include <libxml/xmlversion.h>
#ifndef LIBXML_TREE_ENABLED
# error libxml was not configured with DOM tree support
#endif
#ifndef LIBXML_OUTPUT_ENABLED
# error libxml was not configured with serialization support
#endif
// Because libxml2 is a C library, we need a couple things to make it work
// well with modern C++:
// 1) a ScopeGuard-like type to handle cleanup functions; and
// 2) an exception type that transforms the library's errors.
// ScopeGuard-like type to handle C library cleanup functions.
template <typename F>
class [[nodiscard]] scope_exit
{
public:
// C++20: Constructor can (and should) be [[nodiscard]].
/*[[nodiscard]]*/ constexpr explicit scope_exit(F&& f) :
f_{std::move(f)}
{}
~scope_exit()
{
f_();
}
// Non-copyable, non-movable.
scope_exit(scope_exit const&) = delete;
scope_exit(scope_exit&&) = delete;
auto operator=(scope_exit const&) -> scope_exit& = delete;
auto operator=(scope_exit&&) -> scope_exit& = delete;
private:
F f_;
};
// Exception that gets last libxml2 error.
class libxml_error : public std::runtime_error
{
public:
libxml_error() : libxml_error(std::string{}) {}
explicit libxml_error(std::string message) :
std::runtime_error{make_message_(std::move(message))}
{}
private:
static auto make_message_(std::string message) -> std::string
{
if (auto const last_error = ::xmlGetLastError(); last_error)
{
if (not message.empty())
message += ": ";
message += last_error->message;
}
return message;
}
};
auto add_text(::xmlNode* node, ::xmlChar const* content)
{
// Create a new text node with the desired content.
auto const text_node = ::xmlNewText(content);
if (not text_node)
throw libxml_error{"failed to create text node"};
// Try to add it to the node. If it succeeds, that node will take
// ownership of the text node. If it fails, we have to clean up the text
// node ourselves first, then we can throw.
if (auto const res = ::xmlAddChild(node, text_node); not res)
{
::xmlFreeNode(text_node);
throw libxml_error{"failed to add text node"};
}
return text_node;
}
auto main() -> int
{
// Set this to true if you don't want the XML declaration.
constexpr auto no_xml_declaration = false;
try
{
// Initialize libxml.
::xmlInitParser();
LIBXML_TEST_VERSION
auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};
// Create a new document.
auto doc = ::xmlNewDoc(reinterpret_cast<::xmlChar const*>(u8"1.0"));
if (not doc)
throw libxml_error{"failed to create document"};
auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};
// Create the root element.
auto root = ::xmlNewNode(nullptr,
reinterpret_cast<::xmlChar const*>(u8"root"));
if (not root)
throw libxml_error{"failed to create root element"};
::xmlDocSetRootElement(doc, root); // doc now owns root
// Add whitespace. Unless you know the whitespace is not significant,
// you should do this manually, rather than relying on automatic
// indenting.
add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n "));
// Add the child element.
if (auto const res = ::xmlNewTextChild(root, nullptr,
reinterpret_cast<::xmlChar const*>(u8"element"),
reinterpret_cast<::xmlChar const*>(
u8"\n Some text here\n "));
not res)
throw libxml_error{"failed to create child text element"};
// Add whitespace.
add_text(root, reinterpret_cast<::xmlChar const*>(u8"\n"));
// Output tree. Note that the output is UTF-8 in all cases. If you
// want something different, use xmlSaveFileEnc() or the second
// argument of xmlSaveDoc().
if constexpr (no_xml_declaration)
{
auto const save_context = ::xmlSaveToFilename("-", nullptr,
XML_SAVE_NO_DECL);
auto const save_context_cleanup = scope_exit{[save_context] {
::xmlSaveClose(save_context); }};
if (auto const res = ::xmlSaveDoc(save_context, doc); res == -1)
throw libxml_error{"failed to write tree to stdout"};
}
else
{
if (auto const res = ::xmlSaveFile("-", doc); res == -1)
throw libxml_error{"failed to write tree to stdout"};
}
}
catch (std::exception const& x)
{
std::cerr << "ERROR: " << x.what() << '\n';
return EXIT_FAILURE;
}
}
|
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.
| #Free_Pascal | Free Pascal | program overwriteFile(input, output, stdErr);
{$mode objFPC} // for exception treatment
uses
sysUtils; // for applicationName, getTempDir, getTempFileName
// also: importing sysUtils converts all run-time errors to exceptions
resourcestring
hooray = 'Hello world!';
var
FD: text;
begin
// on a Debian GNU/Linux distribution,
// this will write to /tmp/overwriteFile00000.tmp (or alike)
assign(FD, getTempFileName(getTempDir(false), applicationName()));
try
rewrite(FD); // could fail, if user has no permission to write
writeLn(FD, hooray);
finally
close(FD);
end;
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Open "output.txt" For Output As #1
Print #1, "This is a string"
Close #1 |
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)
| #RPG | RPG |
//-Static array
//--def of 10 el array of integers, initialised to zeros
D array...
D s 10i 0 dim(10)
D inz
//--def an el
D el_1...
D s 10i 0 inz
/free
//-assign first el
//--first element of RPG array is indexed with 1
array(1) = 111;
//-get first el of array
el_1 = array(1);
//--display it
dsply ('First el of array='+%char(el_1));
//--displays: First el of array=111
//---or shorter, without "el_1"
dsply ('First el of array='+%char(array(1)));
//--displays: First el of array=111
/end-free
|
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.
| #COBOL | COBOL |
identification division.
program-id. wr-float.
environment division.
input-output section.
file-control.
select report-file assign "float.txt"
organization sequential.
data division.
file section.
fd report-file
report is floats.
working-storage section.
1 i binary pic 9(4).
1 x-values comp-2.
2 value 1.0.
2 value 2.0.
2 value 3.0.
2 value 1.0e11.
1 redefines x-values comp-2.
2 x occurs 4.
1 comp-2.
2 y occurs 4.
report section.
rd floats.
1 float-line type de.
2 line plus 1.
3 column 1 pic -9.99e+99 source x(i).
2 column 12 pic -9.9999e+99 source y(i).
procedure division.
begin.
open output report-file
initiate floats
perform varying i from 1 by 1
until i > 4
compute y(i) = function sqrt (x(i))
generate float-line
end-perform
terminate floats
close report-file
stop run
.
end program wr-float.
|
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.
| #Latitude | Latitude | use 'format importAllSigils.
doors := Object clone.
doors missing := { False. }.
doors check := {
self slot ($1 ordinal).
}.
doors toggle := {
self slot ($1 ordinal) = self slot ($1 ordinal) not.
}.
1 upto 101 do {
takes '[i].
local 'j = i.
while { j <= 100. } do {
doors toggle (j).
j = j + i.
}.
}.
$stdout printf: ~fmt "The open doors are: ~A", 1 upto 101 filter { doors check. } to (Array). |
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>
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | USER>set writer=##class(%XML.Writer).%New()
USER>set writer.Charset="UTF-8"
USER>Set writer.Indent=1
USER>Set writer.IndentChars=" "
USER>set sc=writer.OutputToString()
USER>set sc=writer.RootElement("root")
USER>set sc=writer.Element("element")
USER>set sc=writer.WriteChars("Some text here")
USER>set sc=writer.EndElement()
USER>set sc=writer.EndRootElement()
USER>Write writer.GetXMLString()
<?xml version="1.0" encoding="UTF-8"?>
<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>
| #Clojure | Clojure |
(require '[clojure.data.xml :as xml])
(def xml-example (xml/element :root {} (xml/element :element {} "Some text here")))
(with-open [out-file (java.io.OutputStreamWriter.
(java.io.FileOutputStream. "/tmp/output.xml") "UTF-8")]
(xml/emit xml-example out-file))
|
http://rosettacode.org/wiki/Write_entire_file | Write entire file | Task
(Over)write a file so that it contains a string.
The reverse of Read entire file—for when you want to update or create a file which you would read in its entirety all at once.
| #Frink | Frink |
w = new Writer["test.txt"]
w.print["I am the captain now."]
w.close[]
|
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.
| #Gambas | Gambas | Public Sub Main()
File.Save(User.home &/ "test.txt", "(Over)write a file so that it contains a string.")
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.
| #Go | Go | import "io/ioutil"
func main() {
ioutil.WriteFile("path/to/your.file", []byte("data"), 0644)
} |
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)
| #Ruby | Ruby | # create an array with one object in it
a = ['foo']
# the Array#new method allows several additional ways to create arrays
# push objects into the array
a << 1 # ["foo", 1]
a.push(3,4,5) # ["foo", 1, 3, 4, 5]
# set the value at a specific index in the array
a[0] = 2 # [2, 1, 3, 4, 5]
# a couple of ways to set a slice of the array
a[0,3] = 'bar' # ["bar", 4, 5]
a[1..-1] = 'baz' # ["bar", "baz"]
a[0] = nil # [nil, "baz"]
a[0,1] = nil # ["baz"]
# retrieve an element
puts a[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.
| #Common_Lisp | Common Lisp | (with-open-file (stream (make-pathname :name "filename") :direction :output)
(let* ((x (make-array 4 :initial-contents '(1 2 3 1e11)))
(y (map 'vector 'sqrt x))
(xprecision 3)
(yprecision 5)
(fmt (format nil "~~,1,~d,,G~~12t~~,~dG~~%" xprecision yprecision)))
(map nil (lambda (a b)
(format stream fmt a b)) x y))) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #Lhogho | Lhogho | to doors
;Problem 100 Doors
;Lhogho
for "p [1 100]
[
make :p "false
]
for "a [1 100 1]
[
for "b [:a 100 :a]
[
if :b < 101
[
make :b not thing :b
]
]
]
for "c [1 100]
[
if thing :c
[
(print "door :c "is "open)
]
]
end
doors |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Common_Lisp | Common Lisp | (let* ((doc (dom:create-document 'rune-dom:implementation nil nil nil))
(root (dom:create-element doc "root"))
(element (dom:create-element doc "element"))
(text (dom:create-text-node doc "Some text here")))
(dom:append-child element text)
(dom:append-child root element)
(dom:append-child doc root)
(dom:map-document (cxml:make-rod-sink) 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>
| #D | D | module xmltest ;
import std.stdio ;
import std.xml ;
void main() {
auto doc = new Document("root") ;
//doc.prolog = q"/<?xml version="1.0"?>/" ; // default
doc ~= new Element("element", "Some text here") ;
writefln(doc) ;
// output: <?xml version="1.0"?><root><element>Some text here</element></root>
} |
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.
| #Groovy | Groovy | new File("myFile.txt").text = """a big string
that can be
splitted over lines
"""
|
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.
| #Haskell | Haskell | main :: IO ( )
main = do
putStrLn "Enter a string!"
str <- getLine
putStrLn "Where do you want to store this string ?"
myFile <- getLine
appendFile myFile 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.
| #J | J | characters fwrite filename |
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
| #8th | 8th |
\ Load the XML text into the var 'x':
quote *
<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>
* xml:parse var, x
\ print only xml nodes which have a tag of 'Student' and whose attributes are not empty
: .xml \ xml --
xml:tag@ "Student" s:cmp if drop ;; then
xml:attrs null? if drop ;; then
"Name" m:@ . cr drop ;
\ Iterate over the XML document in the var 'x'
x @ ' .xml xml:each bye
|
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)
| #Run_BASIC | Run BASIC | print "Enter array 1 greater than 0"; : input a1
print "Enter array 2 greater than 0"; : input a2
dim chrArray$(max(a1,1),max(a2,1))
dim numArray(max(a1,1),max(a2,1))
chrArray$(1,1) = "Hello"
numArray(1,1) = 987.2
print chrArray$(1,1);" ";numArray(1,1) |
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.
| #D | D | import std.file, std.conv, std.string;
void main() {
auto x = [1.0, 2, 3, 1e11];
auto y = [1.0, 1.4142135623730951,
1.7320508075688772, 316227.76601683791];
int xPrecision = 3,
yPrecision = 5;
string tmp;
foreach (i, fx; x)
tmp ~= format("%." ~ text(xPrecision) ~ "g %." ~
text(yPrecision) ~ "g\r\n", fx, y[i]);
write("float_array.txt", tmp);
} |
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.
| #Liberty_BASIC | Liberty BASIC | dim doors(100)
for pass = 1 to 100
for door = pass to 100 step pass
doors(door) = not(doors(door))
next door
next pass
print "open doors ";
for door = 1 to 100
if doors(door) then print door;" ";
next door |
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>
| #E | E | def document := <unsafe:javax.xml.parsers.makeDocumentBuilderFactory> \
.newInstance() \
.newDocumentBuilder() \
.getDOMImplementation() \
.createDocument(null, "root", null)
def root := document.getDocumentElement()
root.appendChild(
def element := document.createElement("element"))
element.appendChild(
document.createTextNode("Some text here"))
println(document.saveXML(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>
| #F.23 | F# | open System.Xml
[<EntryPoint>]
let main argv =
let xd = new XmlDocument()
// Create the required nodes:
xd.AppendChild (xd.CreateXmlDeclaration("1.0", null, null)) |> ignore
let root = xd.AppendChild (xd.CreateNode("element", "root", ""))
let element = root.AppendChild (xd.CreateElement("element", "element", ""))
element.AppendChild (xd.CreateTextNode("Some text here")) |> ignore
// The same can be accomplished with:
// xd.LoadXml("""<?xml version="1.0"?><root><element>Some text here</element></root>""")
let xw = new XmlTextWriter(System.Console.Out)
xw.Formatting <- Formatting.Indented
xd.WriteContentTo(xw)
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.
| #Java | Java | import java.io.*;
public class Test {
public static void main(String[] args) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("test.txt"))) {
bw.write("abc");
}
}
} |
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.
| #Julia | Julia | function writeFile(filename, data)
f = open(filename, "w")
write(f, data)
close(f)
end
writeFile("test.txt", "Hi there.") |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program inputXml64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/* program constantes */
.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 xmlNode */
.struct 0
xmlNode_private: // application data
.struct xmlNode_private + 8
xmlNode_type: // type number, must be second !
.struct xmlNode_type + 8
xmlNode_name: // the name of the node, or the entity
.struct xmlNode_name + 8
xmlNode_children: // parent->childs link
.struct xmlNode_children + 8
xmlNode_last: // last child link
.struct xmlNode_last + 8
xmlNode_parent: // child->parent link
.struct xmlNode_parent + 8
xmlNode_next: // next sibling link
.struct xmlNode_next + 8
xmlNode_prev: // previous sibling link
.struct xmlNode_prev + 8
xmlNode_doc: // the containing document
.struct xmlNode_doc + 8
xmlNode_ns: // pointer to the associated namespace
.struct xmlNode_ns + 8
xmlNode_content: // the content
.struct xmlNode_content + 8
xmlNode_properties: // properties list
.struct xmlNode_properties + 8
xmlNode_nsDef: // namespace definitions on this node
.struct xmlNode_nsDef + 8
xmlNode_psvi: // for type/PSVI informations
.struct xmlNode_psvi + 8
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 x0,qAdrszText // text buffer
mov x1,#LGSZTEXT // text size
mov x2,#0 // param 3
mov x3,#0 // param 4
mov x4,#0 // param 5
bl xmlReadMemory // read text in document
cmp x0,#0 // error ?
beq 99f
mov x19,x0 // doc address
mov x0,x19
bl xmlDocGetRootElement // search root return in x0
bl affElement // display elements
mov x0,x19
bl xmlFreeDoc
bl xmlCleanupParser
ldr x0,qAdrszMessEndpgm
bl affichageMess
b 100f
99: // error
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessError: .quad szMessError
qAdrszMessEndpgm: .quad szMessEndpgm
qAdrszText: .quad szText
qAdrszCarriageReturn: .quad szCarriageReturn
/******************************************************************/
/* display name of student */
/******************************************************************/
/* x0 contains the address of node */
affElement:
stp x24,lr,[sp,-16]! // save registers
mov x24,x0 // save node
1:
ldr x12,[x24,#xmlNode_type] // type ?
cmp x12,#XML_ELEMENT_NODE
bne 2f
ldr x0,[x24,#xmlNode_name] // name = "Student" ?
ldr x1,qAdrszLibExtract
bl comparString
cmp x0,#0
bne 2f // no
mov x0,x24
ldr x1,qAdrszLibName // load property of "Name"
bl xmlHasProp
cmp x0,#0
beq 2f
ldr x1,[x0,#xmlNode_children] // children node of property name
ldr x0,[x1,#xmlNode_content] // and address of content
bl affichageMess // for display
ldr x0,qAdrszCarriageReturn
bl affichageMess
2:
ldr x0,[x24,#xmlNode_children] // node have children ?
cbz x0,3f
bl affElement // yes -> call procedure
3:
ldr x1,[x24,#xmlNode_next] // other element ?
cmp x1,#0
beq 100f // no -> end procedure
mov x24,x1 // else loop with next element
b 1b
100:
ldp x24,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrszLibName: .quad szLibName
qAdrszLibExtract: .quad szLibExtract
/************************************/
/* Strings comparaison */
/************************************/
/* x0 et x1 contains strings addresses */
/* x0 return 0 dans x0 if equal */
/* return -1 if string x0 < string x1 */
/* return 1 if string x0 > string x1 */
comparString:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,#0 // indice
1:
ldrb w3,[x0,x2] // one byte string 1
ldrb w4,[x1,x2] // one byte string 2
cmp w3,w4
blt 2f // less
bgt 3f // greather
cmp w3,#0 // 0 final
beq 4f // equal and end
add x2,x2,#1 //
b 1b // else loop
2:
mov x0,#-1 // less
b 100f
3:
mov x0,#1 // greather
b 100f
4:
mov x0,#0 // equal
b 100f
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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)
| #Rust | Rust | let a = [1, 2, 3]; // immutable array
let mut m = [1, 2, 3]; // mutable array
let zeroes = [0; 200]; // creates an array of 200 zeroes |
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.
| #11l | 11l | V games = [‘12’, ‘13’, ‘14’, ‘23’, ‘24’, ‘34’]
V results = ‘000000’
F numberToBase(=n, b)
I n == 0
R ‘0’
V digits = ‘’
L n != 0
digits ‘’= String(Int(n % b))
n I/= b
R reversed(digits)
F nextResult()
I :results == ‘222222’
R 0B
V res = Int(:results, radix' 3) + 1
:results = numberToBase(res, 3).zfill(6)
R 1B
V points = [[0] * 10] * 4
L
V records = [0] * 4
L(i) 0 .< games.len
S results[i]
‘2’
records[games[i][0].code - ‘1’.code] += 3
‘1’
records[games[i][0].code - ‘1’.code]++
records[games[i][1].code - ‘1’.code]++
‘0’
records[games[i][1].code - ‘1’.code] += 3
records.sort()
L(i) 4
points[i][records[i]]++
I !nextResult()
L.break
print(|‘POINTS 0 1 2 3 4 5 6 7 8 9
-------------------------------------------------------------’)
V places = [‘1st’, ‘2nd’, ‘3rd’, ‘4th’]
L(i) 4
print(places[i], end' ‘ place ’)
L(j) 10
print(‘#<5’.format(points[3 - i][j]), end' ‘’)
print() |
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.
| #Delphi | Delphi |
program Write_float_arrays_to_a_text_file;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.IoUtils;
function ToString(v: TArray<Double>): TArray<string>;
var
fmt: TFormatSettings;
begin
fmt := TFormatSettings.Create('en-US');
SetLength(Result, length(v));
for var i := 0 to High(v) do
Result[i] := v[i].tostring(ffGeneral, 5, 3, fmt);
end;
function Merge(a, b: TArray<string>): TArray<string>;
begin
SetLength(Result, length(a));
for var i := 0 to High(a) do
Result[i] := a[i] + ^I + b[i];
end;
var
x, y: TArray<Double>;
begin
x := [1, 2, 3, 1e11];
y := [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791];
TFile.WriteAllLines('FloatArrayColumns.txt', Merge(ToString(x), ToString(y)));
end. |
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.
| #Lily | Lily | var doors = List.fill(100, false)
for i in 0...99:
for j in i...99 by i + 1:
doors[j] = !doors[j]
# The type must be specified since the list starts off empty.
var open_doors: List[Integer] = []
doors.each_index{|i|
if doors[i]:
open_doors.push(i + 1)
}
print($"Open doors: ^(open_doors)") |
http://rosettacode.org/wiki/XML/DOM_serialization | XML/DOM serialization | Create a simple DOM and having it serialize to:
<?xml version="1.0" ?>
<root>
<element>
Some text here
</element>
</root>
| #Factor | Factor | USING: xml.syntax xml.writer ;
<XML <root><element>Some text here</element></root> XML>
pprint-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>
| #Fantom | Fantom |
using xml
class XmlDom
{
public static Void main ()
{
doc := XDoc()
root := XElem("root")
doc.add (root)
child := XElem("element")
child.add(XText("Some text here"))
root.add (child)
doc.write(Env.cur.out)
}
}
|
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.
| #Kotlin | Kotlin | // version 1.1.2
import java.io.File
fun main(args: Array<String>) {
val text = "empty vessels make most noise"
File("output.txt").writeText(text)
} |
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.
| #Lingo | Lingo | ----------------------------------------
-- Saves string as file
-- @param {string} tFile
-- @param {string} tString
-- @return {bool} success
----------------------------------------
on writeFile (tFile, tString)
fp = xtra("fileIO").new()
fp.openFile(tFile, 2)
err = fp.status()
if not (err) then fp.delete()
else if (err and not (err = -37)) then return false
fp.createFile(tFile)
if fp.status() then return false
fp.openFile(tFile, 2)
if fp.status() then return false
fp.writeString(tString)
fp.closeFile()
return true
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.
| #LiveCode | LiveCode |
put "this is a string" into URL "file:~/Desktop/TestFile.txt"
|
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program outputXml64.s */
/* use special library libxml2 */
/* special link gcc with options -I/usr/include/libxml2 -lxml2 */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* 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"
szLibName: .asciz "Name"
szCarriageReturn: .asciz "\n"
tbNames: .quad szName1 // area of pointer string name
.quad szName2
.quad szName3
.quad 0 // area end
tbRemarks: .quad szRemark1 // area of pointer string remark
.quad szRemark2
.quad szRemark3
.quad 0 // area end
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszVersDoc
bl xmlNewDoc // create doc
mov x19,x0 // doc address
mov x0,#0
ldr x1,qAdrszLibCharRem
bl xmlNewNode // create root node
mov x20,x0 // node characterisation address
mov x0,x19 // doc
mov x1,x20 // node root
bl xmlDocSetRootElement
ldr x22,qAdrtbNames
ldr x23,qAdrtbRemarks
mov x24,#0 // loop counter
1: // start loop
mov x0,#0
ldr x1,qAdrszLibChar // create node
bl xmlNewNode
mov x21,x0 // node character
// x0 = node address
ldr x1,qAdrszLibName
ldr x2,[x22,x24,lsl #3] // load name string address
bl xmlNewProp
ldr x0,[x23,x24,lsl #3] // load remark string address
bl xmlNewText
mov x1,x0
mov x0,x21
bl xmlAddChild
mov x0,x20
mov x1,x21
bl xmlAddChild
add x24,x24,#1
ldr x2,[x22,x24,lsl #3] // load name string address
cmp x2,#0 // = zero ?
bne 1b // no -> loop
ldr x0,qAdrszFileName
ldr x1,qAdrszFileMode
bl fopen // file open
cmp x0,#0
blt 99f
mov x24,x0 //FD
mov x1,x19
mov x2,x20
bl xmlDocDump // write doc on the file
mov x0,x24 // close file
bl fclose
mov x0,x19 // close document
bl xmlFreeDoc
bl xmlCleanupParser
ldr x0,qAdrszMessEndpgm
bl affichageMess
b 100f
99: // error
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessError: .quad szMessError
qAdrszMessEndpgm: .quad szMessEndpgm
qAdrszVersDoc: .quad szVersDoc
qAdrszLibCharRem: .quad szLibCharRem
qAdrszLibChar: .quad szLibChar
qAdrszLibName: .quad szLibName
qAdrtbNames: .quad tbNames
qAdrtbRemarks: .quad tbRemarks
qAdrszCarriageReturn: .quad szCarriageReturn
qStdout: .quad STDOUT
qAdrszFileName: .quad szFileName
qAdrszFileMode: .quad szFileMode
/************************************/
/* Strings comparaison */
/************************************/
/* x0 et x1 contains strings addresses */
/* x0 return 0 dans x0 if equal */
/* return -1 if string x0 < string x1 */
/* return 1 if string x0 > string x1 */
comparString:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,#0 // indice
1:
ldrb w3,[x0,x2] // one byte string 1
ldrb w4,[x1,x2] // one byte string 2
cmp w3,w4
blt 2f // less
bgt 3f // greather
cmp w3,#0 // 0 final
beq 4f // equal and end
add x2,x2,#1 //
b 1b // else loop
2:
mov x0,#-1 // less
b 100f
3:
mov x0,#1 // greather
b 100f
4:
mov x0,#0 // equal
b 100f
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
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
| #ActionScript | ActionScript | package
{
import flash.display.Sprite;
public class XMLReading extends Sprite
{
public function XMLReading()
{
var xml:XML = <Students>
<Student Name="April" />
<Student Name="Bob" />
<Student Name="Chad" />
<Student Name="Dave" />
<Student Name="Emily" />
</Students>;
for each(var node:XML in xml..Student)
{
trace(node.@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)
| #Sather | Sather | -- a is an array of INTs
a :ARRAY{INT};
-- create an array of five "void" elements
a := #ARRAY{INT}(5);
-- static creation of an array with three elements
b :ARRAY{FLT} := |1.2, 1.3, 1.4|;
-- accessing an array element
c ::= b[0]; -- syntactic sugar for b.aget(0)
-- set an array element
b[1] := c; -- syntactic sugar for b.aset(1, c)
-- append another array
b := b.append(|5.5|); |
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 | C | #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// to supply to qsort
int compare(const void *a, const void *b) {
int int_a = *((int *)a);
int int_b = *((int *)b);
return (int_a > int_b) - (int_a < int_b);
}
char results[7];
bool next_result() {
char *ptr = results + 5;
int num = 0;
size_t i;
// check if the space has been examined
if (strcmp(results, "222222") == 0) {
return false;
}
// translate the base 3 string back to a base 10 integer
for (i = 0; results[i] != 0; i++) {
int d = results[i] - '0';
num = 3 * num + d;
}
// to the next value to process
num++;
// write the base 3 string (fixed width)
while (num > 0) {
int rem = num % 3;
num /= 3;
*ptr-- = rem + '0';
}
// zero fill the remainder
while (ptr > results) {
*ptr-- = '0';
}
return true;
}
char *games[6] = { "12", "13", "14", "23", "24", "34" };
char *places[4] = { "1st", "2nd", "3rd", "4th" };
int main() {
int points[4][10];
size_t i, j;
strcpy(results, "000000");
for (i = 0; i < 4; i++) {
for (j = 0; j < 10; j++) {
points[i][j] = 0;
}
}
do {
int records[] = { 0, 0, 0, 0 };
for (i = 0; i < 6; 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;
}
}
qsort(records, 4, sizeof(int), compare);
for (i = 0; i < 4; i++) {
points[i][records[i]]++;
}
} while (next_result());
printf("POINTS 0 1 2 3 4 5 6 7 8 9\n");
printf("-----------------------------------------------------------\n");
for (i = 0; i < 4; i++) {
printf("%s place", places[i]);
for (j = 0; j < 10; j++) {
printf("%5d", points[3 - i][j]);
}
printf("\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.
| #Elixir | Elixir | defmodule Write_float_arrays do
def task(xs, ys, fname, precision\\[]) do
xprecision = Keyword.get(precision, :x, 2)
yprecision = Keyword.get(precision, :y, 3)
format = "~.#{xprecision}g\t~.#{yprecision}g~n"
File.open!(fname, [:write], fn file ->
Enum.zip(xs, ys)
|> Enum.each(fn {x, y} -> :io.fwrite file, format, [x, y] end)
end)
end
end
x = [1.0, 2.0, 3.0, 1.0e11]
y = for n <- x, do: :math.sqrt(n)
fname = "filename.txt"
Write_float_arrays.task(x, y, fname)
IO.puts File.read!(fname)
precision = [x: 3, y: 5]
Write_float_arrays.task(x, y, fname, precision)
IO.puts File.read!(fname) |
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.
| #Erlang | Erlang |
-module( write_float_arrays ).
-export( [task/0, to_a_text_file/3, to_a_text_file/4] ).
task() ->
File = "afile",
Xs = [1.0, 2.0, 3.0, 1.0e11],
Ys = [1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791],
Options = [{xprecision, 3}, {yprecision, 5}],
to_a_text_file( File, Xs, Ys, Options ),
{ok, Contents} = file:read_file( File ),
io:fwrite( "File contents: ~p~n", [Contents] ).
to_a_text_file( File, Xs, Ys ) -> to_a_text_file( File, Xs, Ys, [] ).
to_a_text_file( File, Xs, Ys, Options ) ->
Xprecision = proplists:get_value( xprecision, Options, 2 ),
Yprecision = proplists:get_value( yprecision, Options, 2 ),
Format = lists:flatten( io_lib:format("~~.~pg ~~.~pg~n", [Xprecision, Yprecision]) ),
{ok, IO} = file:open( File, [write] ),
[ok = io:fwrite( IO, Format, [X, Y]) || {X, Y} <- lists:zip( Xs, Ys)],
file:close( IO ).
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.