Create an HTML table: Difference between revisions
(→{{header|MATLAB}} / {{header|Octave}}: html table) |
(→{{header|AWK}}: generate HTML table) |
||
Line 124: | Line 124: | ||
<tr><th>4</th><td>396</td><td>762</td><td>633</tr> |
<tr><th>4</th><td>396</td><td>762</td><td>633</tr> |
||
</table> |
</table> |
||
=={{header|AWK}}== |
|||
<lang AWK>#!/usr/bin/awk -f |
|||
BEGIN { |
|||
print "<table>\n <thead align = \"right\">"; |
|||
printf " <tr><th></th><td>X</td><td>Y</td><td>Z</td></tr>\n </thead>\n <tbody align = \"right\">\n"; |
|||
}; |
|||
{ |
|||
printf " <tr><td>%2i</td><td>%5i</td><td>%5i</td><td>%5i</td></tr>\n",NR,$1,$2,$3; |
|||
}; |
|||
END { |
|||
print " </tbody>\n</table>\n"; |
|||
};</lang> |
|||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
Revision as of 22:59, 2 February 2012
You are encouraged to solve this task according to the task description, using any language you may know.
Create an HTML table.
- The table body should have at least three rows of three columns.
- Each of these three columns should be labelled "X", "Y", and "Z".
- An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
- The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
- The numbers should be aligned in the same fashion for all columns.
Ada
<lang Ada>with Ada.Text_IO; with Ada.Numerics.Discrete_Random;
procedure HTML_Table is
use Ada.Text_IO;
function Blanks(N: Natural) return String is begin if N=0 then return ""; else return " " & Blanks(N-1); end if; end Blanks;
package Table is type Four_Digits is mod 10_000; package Rand is new Ada.Numerics.Discrete_Random(Four_Digits); Gen: Rand.Generator;
type object is tagged null record;
procedure Print(T: Object; Rows: Natural); procedure Print_Header(T: Object); procedure Print_Body(T: Object; Rows: Natural); procedure Print_Row(T: Object; Row_Number: Positive); end Table;
package body Table is
procedure Print_Row(T: Object; Row_Number: Positive) is begin
Put(Blanks(4) & "" & Positive'Image(Row_Number) & "");
for I in 1 .. 3 loop
Put("" & Four_Digits'Image(Rand.Random(Gen)) & "");
end loop;
Put_Line(""); end Print_Row; procedure Print_Body(T: Object; Rows: Natural) is begin Put_Line(Blanks(2)&"<tbody align = ""right"">"); for I in 1 .. Rows loop T.Print_Row(I); end loop; Put_Line(Blanks(2)&"</tbody>"); end Print_Body; procedure Print_Header(T: Object) is begin Put_Line(Blanks(2) & "<thead align = ""right"">"); Put_Line(Blanks(4) & "XY" & "Z");
Put_Line(Blanks(2) & "</thead>"); end Print_Header;
procedure Print(T: Object; Rows: Natural) is begin
Put_Line("
"); T.Print_Header; T.Print_Body(Rows); Put_Line("");
end Print;
begin Rand.Reset(Gen); end Table;
T: Table.Object;
begin
T.Print(Rows => 4);
end HTML_Table;</lang>
Each time you run the program, you get different random values for the table. Here is a sample output:
<lang html5>
<thead align = "right"></thead> <tbody align = "right">
</tbody>
X | Y | Z | |
1 | 5091 | 395 | 6319 |
2 | 7099 | 746 | 173 |
3 | 1701 | 3897 | 2124 |
4 | 8539 | 1696 | 1417 |
</lang>
Viewing the output with Lynx:
X Y Z 1 5091 395 6319 2 7099 746 173 3 1701 3897 2124 4 8539 1696 1417
AutoHotkey
<lang AutoHotkey>out =
Loop 4
out .= "`r`n" out .= "`r`nX | Y | Z | |
---|---|---|---|
" A_Index " | " Rand() " | " Rand() " | " Rand() " |
"
MsgBox % clipboard := out
Rand(u=1000){
Random, n, 1, % u return n
}</lang> Output:
X | Y | Z | |
---|---|---|---|
1 | 289 | 556 | 43 |
2 | 102 | 100 | 971 |
3 | 582 | 295 | 264 |
4 | 396 | 762 | 633 |
AWK
<lang AWK>#!/usr/bin/awk -f BEGIN {
print "
\n <thead align = \"right\">"; printf " \n </thead>\n <tbody align = \"right\">\n";};
{
printf " \n",NR,$1,$2,$3;};
END {
print " </tbody>\nX | Y | Z | |
%2i | %5i | %5i | %5i |
\n";
};</lang>
BBC BASIC
Uses BBC BASIC's *spool command to create a file. <lang bbcbasic> ncols% = 3
nrows% = 4 *spool temp.htm PRINT "<html><head></head><body>"
PRINT "
" FOR row% = 0 TO nrows% IF row% = 0 THEN PRINT "" ;ELSEPRINT "" ;
ENDIF FOR col% = 1 TO ncols% IF row% = 0 THENPRINT "" ;
ELSEPRINT "" ;
ENDIF NEXT col%PRINT "" NEXT row% PRINT "
" ; row% " | " CHR$(87 + col%) " | " ; RND(9999) " |
---|
"
PRINT "</body></html>" *spool SYS "ShellExecute", @hwnd%, 0, "temp.htm", 0, 0, 1
</lang> Output:
<html><head></head><body> <table border=1 cellpadding=10 cellspacing=0> <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr> <tr><th>1</th><td align="right">2791</td><td align="right">8011</td><td align="right">9582</td> </tr> <tr><th>2</th><td align="right">6793</td><td align="right">6863</td><td align="right">4790</td> </tr> <tr><th>3</th><td align="right">8064</td><td align="right">2626</td><td align="right">3917</td> </tr> <tr><th>4</th><td align="right">2660</td><td align="right">8776</td><td align="right">6805</td> </tr> </table> </body></html>
C
<lang C>#include <stdio.h>
- include <stdlib.h>
int main() { int i;
printf("
" "");for (i = 0; i < 4; i++) {
printf("", i,rand() % 10000, rand() % 10000, rand() % 10000); }
printf("X | Y | Z | |
---|---|---|---|
%d | %d | %d | %d |
");
return 0;
}</lang>output (wiki doesn't like tbody/thead tags):
X | Y | Z | |
---|---|---|---|
0 | 2777 | 886 | 9383 |
1 | 8335 | 7793 | 6915 |
2 | 6649 | 492 | 5386 |
3 | 27 | 2362 | 1421 |
C++
<lang cpp>#include <fstream>
- include <boost/array.hpp>
- include <string>
- include <cstdlib>
- include <ctime>
- include <sstream>
void makeGap( int gap , std::string & text ) {
for ( int i = 0 ; i < gap ; i++ ) text.append( " " ) ;
}
int main( ) {
boost::array<char , 3> chars = { 'X' , 'Y' , 'Z' } ; int headgap = 3 ; int bodygap = 3 ; int tablegap = 6 ; int rowgap = 9 ; std::string tabletext( "<html>\n" ) ; makeGap( headgap , tabletext ) ; tabletext += "<head></head>\n" ; makeGap( bodygap , tabletext ) ; tabletext += "<body>\n" ; makeGap( tablegap , tabletext ) ;
tabletext += "
\n" ; makeGap( tablegap + 1 , tabletext ) ; tabletext += "<thead align=\"right\">\n" ; makeGap( tablegap, tabletext ) ; tabletext += "" ;for ( int i = 0 ; i < 3 ; i++ ) {tabletext += "" ; } tabletext += "\n" ; makeGap( tablegap + 1 , tabletext ) ; tabletext += "</thead>" ; makeGap( tablegap + 1 , tabletext ) ; tabletext += "<tbody align=\"right\">\n" ; srand( time( 0 ) ) ; for ( int row = 0 ; row < 5 ; row++ ) { makeGap( rowgap , tabletext ) ; std::ostringstream oss ; tabletext += "" ; } tabletext += "\n" ; } makeGap( tablegap + 1 , tabletext ) ; tabletext += "</tbody>\n" ; makeGap( tablegap , tabletext ) ; tabletext += "
" ;
tabletext += *(chars.begin( ) + i ) ;tabletext += " | |
" ;
oss << row ; tabletext += oss.str( ) ; for ( int col = 0 ; col < 3 ; col++ ) { oss.str( "" ) ; int randnumber = rand( ) % 10000 ; oss << randnumber ; tabletext += " | " ;
tabletext.append( oss.str( ) ) ; tabletext += " |
\n" ;
makeGap( bodygap , tabletext ) ; tabletext += "</body>\n" ; tabletext += "</html>\n" ; std::ofstream htmltable( "testtable.html" , std::ios::out | std::ios::trunc ) ; htmltable << tabletext ; htmltable.close( ) ; return 0 ;
}</lang> Output ( of testtable.html ): <LANG html5><html>
<head></head> <body><thead align="right">
</thead> <tbody align="right">
</tbody>
X | Y | Z | |
0 | 1274 | 6847 | 352 |
1 | 846 | 6577 | 4612 |
2 | 7543 | 1644 | 8143 |
3 | 4928 | 5714 | 8186 |
4 | 3436 | 7493 | 9344 |
</body>
</html> </LANG>
C#
<lang csharp>using System; using System.Text;
namespace prog { class MainClass { public static void Main (string[] args) { StringBuilder s = new StringBuilder(); Random rnd = new Random();
s.AppendLine("
"); s.AppendLine("<thead align = \"right\">"); s.Append("");for(int i=0; i<3; i++)
s.Append(""); s.AppendLine(""); s.AppendLine("</thead>"); s.AppendLine("<tbody align = \"right\">"); for( int i=0; i<3; i++ ) { s.Append("");for( int j=0; j<3; j++ )
s.Append(""); s.AppendLine(""); } s.AppendLine("</tbody>"); s.AppendLine("" + "XYZ"[i] + " | |
"+i+" | "+rnd.Next(10000)+" |
");
Console.WriteLine( s ); } } }</lang>
CoffeeScript
<lang coffeescript>
- This is one of many ways to create a table. CoffeeScript plays nice
- with any templating solution built for JavaScript, and of course you
- can build tables in the browser using DOM APIs. This approach is just
- brute force string manipulation.
table = (header_row, rows) ->
"""#{header_row} #{rows.join '\n'}
"""
tr = (cells) -> "#{cells.join }" th = (s) -> "#{s}" td = (s) -> "#{s}"
rand_n = -> Math.floor Math.random() * 10000
header_cols = [, 'X', 'Y', 'Z'] header_row = tr (th s for s in header_cols)
rows = [] for i in [1..5]
rows.push tr [ th(i) td rand_n() td rand_n() td rand_n() ]
html = table header_row, rows console.log html </lang>
output:
X | Y | Z | |
---|---|---|---|
1 | 1575 | 7445 | 4544 |
2 | 3827 | 5029 | 235 |
3 | 10 | 9363 | 4381 |
4 | 297 | 2463 | 5745 |
5 | 4063 | 6726 | 1093 |
D
<lang d>import std.stdio, std.random;
void main() {
writeln(`
`); writeln("");foreach (i; 0 .. 4)writefln("",
i, uniform(0,1000), uniform(0,1000), uniform(0,1000));writeln("
X | Y | Z | |
---|---|---|---|
%d | %d | %d | %d |
");
}</lang> Output:
X | Y | Z | |
---|---|---|---|
0 | 524 | 739 | 847 |
1 | 13 | 813 | 782 |
2 | 926 | 580 | 663 |
3 | 309 | 816 | 750 |
Delphi
<lang Delphi>program CreateHTMLTable;
{$APPTYPE CONSOLE}
uses SysUtils;
function AddTableRow(aRowNo: Integer): string; begin
Result := Format(' %d%d%d%d',
[aRowNo, Random(10000), Random(10000), Random(10000)]);
end;
var
i: Integer;
begin
Randomize;
Writeln('
'); Writeln(' ');for i := 1 to 4 do Writeln(AddTableRow(i));Writeln('
X | Y | Z |
---|
');
Readln;
end.</lang>
Output:
<lang html5>
X | Y | Z | |
---|---|---|---|
1 | 7371 | 2659 | 1393 |
2 | 6710 | 5025 | 5203 |
3 | 1316 | 1599 | 2086 |
4 | 4785 | 6612 | 5042 |
</lang>
Euphoria
<lang euphoria>puts(1,"
\n") puts(1," \n")for i = 1 to 3 do
printf(1," ",i)for j = 1 to 3 doprintf(1,"",rand(10000))
end forputs(1,"\n") end for puts(1,"
X | Y | Z | |
---|---|---|---|
%d | %d |
")</lang>
Sample output:
<lang html5>
X | Y | Z | |
---|---|---|---|
1 | 7978 | 7376 | 2382 |
2 | 3632 | 1947 | 8900 |
3 | 4098 | 1563 | 2762 |
</lang>
Go
html/template is a package in the standard library. <lang go>package main
import (
"fmt" "os" "html/template"
)
type Row struct {
X, Y, Z int
}
var tmpl = `
Template:Range $ix, $row := .Template:EndX | Y | Z | |
---|---|---|---|
Template:$ix | Template:$row.X | Template:$row.Y | Template:$row.Z |
`
func main() {
// create template ct := template.Must(template.New("").Parse(tmpl))
// make up data data := make([]Row, 4) for r := range data { data[r] = Row{r * 3, r*3 + 1, r*3 + 2} }
// open output file hf, err := os.Create("table.html") if err != nil { fmt.Println(err) return } defer hf.Close()
// apply template to data if err := ct.Execute(hf, data); err != nil { fmt.Println(err) }
}</lang> Output in table.html: <lang html5>
X | Y | Z | |
---|---|---|---|
0 | 0 | 1 | 2 |
1 | 3 | 4 | 5 |
2 | 6 | 7 | 8 |
3 | 9 | 10 | 11 |
</lang>
Icon and Unicon
<lang Icon>procedure main()
printf("
\n ")every r := 1 to 4 do {
printf("\n ",r) every 1 to 3 do printf("",?9999) # random 4 digit numbers per cell}printf("\n
X | Y | Z | |
---|---|---|---|
%d | %d |
\n")
end
link printf </lang>
Sample Output:<lang html5>
X | Y | Z | |
---|---|---|---|
1 | 3129 | 3294 | 7013 |
2 | 5045 | 169 | 5761 |
3 | 7001 | 963 | 4183 |
4 | 1695 | 1158 | 1240 |
</lang>
J
We can define:
<lang j>ele=:4 :0
nm=. x-.LF lf=. x-.nm ;('<',nm,'>') ,L:0 y ,L:0 '</',nm,'>',lf
)
hTbl=:4 :0
rows=. 'td' <@ele"1 ":&.>y 'table' ele ('tr',LF) <@ele ('th' ele x); rows
)</lang>
With these definitions:
<lang j> (;;:'X Y Z') hTbl ":&.>(i.5),.i.5 3
X | Y | Z | |
---|---|---|---|
0 | 0 | 1 | 2 |
1 | 3 | 4 | 5 |
2 | 6 | 7 | 8 |
3 | 9 | 10 | 11 |
4 | 12 | 13 | 14 |
</lang>
Or, if running under jhs:
<lang j>jhtml (;;:'X Y Z') hTbl ":&.>(i.5),.i.5 3</lang>
to display the table inline, as html.
Java
This example assumes the header row is the first row in the given array and does not add row numbers. They will need to be added by the programmer when constructing the array. <lang java5>public class HTML {
public static String array2HTML(Object[][] array){ StringBuilder html = new StringBuilder(
"
"); for(Object elem:array[0]){ html.append("");} for(int i = 1; i < array.length; i++){ Object[] row = array[i];
html.append(""); for(Object elem:row){ html.append("");}
html.append(""); } html.append("" + elem.toString() + " |
---|
" + elem.toString() + " |
");
return html.toString(); }
public static void main(String[] args){ Object[][] ints = {{"","X","Y","Z"},{1,1,2,3},{2,4,5,6},{3,7,8,9},{4,10,11,12}}; System.out.println(array2HTML(ints)); } }</lang> Output:
<lang html5>
X | Y | Z | |
---|---|---|---|
1 | 1 | 2 | 3 |
2 | 4 | 5 | 6 |
3 | 7 | 8 | 9 |
4 | 10 | 11 | 12 |
</lang>
JavaScript
<lang html><html><head><title>Table maker</title><script type="application/javascript">
// normally, don't do this: at least name it something other than "a" Node.prototype.a = function (e) { this.appendChild(e); return this }
function ce(tag, txt) { var x = document.createElement(tag); x.textContent = (txt === undefined) ? : txt; return x; }
function make_table(cols, rows) { var tbl = ce('table', ), tr = ce('tr'), th;
tbl.a(tr.a(ce('th')));
var z = 'Z'.charCodeAt(0); for (var l = z - cols + 1; l <= z; l++) tr.a(ce('th', String.fromCharCode(l)));
for (var r = 1; r <= rows; r++) { tbl.a(tr = ce('tr').a(ce('th', r))); for (var c = 0; c < cols; c++) tr.a(ce('td', Math.floor(Math.random() * 10000))); }
document.body .a(ce('style', 'td, th {border: 1px solid #696;' + 'padding:.4ex} td {text-align: right }' + 'table { border-collapse: collapse}')) .a(tbl); } </script></head> <body><script>make_table(5, 4)</script></body></html></lang>
Liberty BASIC
This creates and saves an html file, then calls web browser to display it.
A time delay is needed to allow this, then the file is deleted.
<lang lb>
nomainwin
quote$ =chr$( 34)
html$ ="<html><head></head><body>"
html$ =html$ +"
"for i =1 to 4 d1$ =str$( i) d2$ =str$( int( 10000 *rnd( 1))) d3$ =str$( int( 10000 *rnd( 1))) d4$ =str$( int( 10000 *rnd( 1)))html$ =html$ +""
next ihtml$ =html$ +"
X | Y | Z | |
---|---|---|---|
"; d1$; " | " +d2$ +" | " +d3$ +" | " +d4$ +" |
"
html$ =html$ +"</body></html>"
open "table.html" for output as #o #o html$; close #o
address$ ="table.html" run "explorer.exe "; address$
timer 5000, [on] wait [on] timer 0
kill "table.html"
wait
sub quit w$
close #w$ end
end sub </lang>
Mathematica
<lang Mathematica>x := RandomInteger[10];
Print["
", "\n",""] Scan[Print[""] & , Range[3]] Print["X | Y | Z | |
---|---|---|---|
", #, " | ", x, " | ", x, " | "," |
"]</lang>
Output :
<table> <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr> <tr><td>1</td><td>6</td><td>10</td><td></td></tr> <tr><td>2</td><td>1</td><td>10</td><td></td></tr> <tr><td>3</td><td>6</td><td>7</td><td></td></tr> </table>
MATLAB / Octave
<lang matlab>function htmltable(fid,table,Label)
fprintf(fid,'
\n <thead align = "right">\n'); if nargin<3, fprintf(fid,' \n </thead>\n <tbody align = "right">\n');elsefprintf(fid,' '); fprintf(fid,'',Label{:}); fprintf(fid,'\n </thead>\n <tbody align = "right">\n'); end; fprintf(fid,' \n', [1:size(table,1);table']); fprintf(fid,' </tbody>\n
X | Y | Z | |
%s | |||
%2i | %5i | %5i | %5i |
\n');
end</lang>
Output:
>> htmltable(1,ceil(rand(5,3)*10000)) <table> <thead align = "right"> <tr><th></th><td>X</td><td>Y</td><td>Z</td></tr> </thead> <tbody align = "right"> <tr><td> 1</td><td> 6639</td><td> 1110</td><td> 296</td></tr> <tr><td> 2</td><td> 4864</td><td> 1252</td><td> 8412</td></tr> <tr><td> 3</td><td> 3800</td><td> 4556</td><td> 3752</td></tr> <tr><td> 4</td><td> 5728</td><td> 6897</td><td> 2157</td></tr> <tr><td> 5</td><td> 2272</td><td> 8503</td><td> 7021</td></tr> </tbody> </table>
Modula-2
<lang modula2>MODULE testCGI;
FROM InOut IMPORT WriteCard, WriteLn, WriteString, WriteBf; FROM Arguments IMPORT ArgTable, GetEnv; FROM Strings IMPORT Assign, Length, String;
VAR EnvVars : ArgTable;
PROCEDURE ReadEnvVar;
VAR Value : String;
i : CARDINAL;
BEGIN
WriteString ('
'); WriteString ('');i := 0; LOOP IF EnvVars^ [i] = NIL THEN EXIT END; Assign (Value, EnvVars^ [i]^);WriteString ('"); WriteLn; INC (i) END; WriteString("
Index | Length | Content |
---|---|---|
');
WriteCard (i, 2);WriteString (' | ');
WriteCard (Length (Value), 3);WriteString (' | '); WriteString (Value); WriteString (" |
");
END ReadEnvVar;
BEGIN
GetEnv (EnvVars); WriteString ('Content-type:text/html'); WriteLn; WriteLn; WriteString ('<html><head>'); WriteString ('<title>CGI with the Mocka Modula-2 compiler</title>'); WriteString ('</head><body>'); WriteLn;
WriteString ('
CGI environment passed along by your browser
');
ReadEnvVar; WriteString ('</body></html>'); WriteLn; WriteBf
END testCGI.</lang>
NewLISP
<lang NewLISP>; file: html-table.lsp
- url
- http://rosettacode.org/wiki/Create_an_HTML_table
- author
- oofoe 2012-01-29
(seed (time-of-day)) ; Initialize random number generator.
- The "tab" variable tracks the HTML indent. "pad" composes a line
- with the appropriate indent and a terminal newline.
(setq tab 0) (define (pad text) (string (dup " " tab) text "\n"))
- NewLISP allows almost any character in an identifier, so I can name
- my functions after the HTML elements they invoke. This one formats a
- single table data cell.
(define ( text) (pad (string "" text "")))
- "" will accept either a number of arguments, each one to be
- formatted as a table cell, or a single list argument, which is
- broken into table cells. For convenience, I format each list item
- with the "" function so I can feed it raw lists.
(define () (let ((data (args)) (s (pad ""))) (if (list? (data 0)) (setq data (data 0))) (inc tab) (dolist (el data) (extend s ( el)))
(dec tab)
(extend s (pad "")) s))
- By defining "" as a macro, I ensure that the rows won't be
- evaluated until I've got the table started, which preserves the
- formatting.
(define-macro ("))) (inc tab) (doargs (row) (extend s (eval row))) (dec tab) (extend s (pad "
"))
s ))
- Test
- rnd ( -$ ) random 1000 mod toString ;
- Build the data we're displaying
- Write the table to standard out
<table> <tr> <td></td> <td>X</td> <td>Y</td> <td>Z</td> </tr> <tr> <td>0</td> <td>289</td> <td>824</td> <td>462</td> </tr> <tr> <td>1</td> <td>49</td> <td>600</td> <td>84</td> </tr> <tr> <td>2</td> <td>511</td> <td>219</td> <td>742</td> </tr> </table>
Table:
X | Y | Z | |
0 | 289 | 824 | 462 |
1 | 49 | 600 | 84 |
2 | 511 | 219 | 742 |
Oz
As a complete web application, using the "Roads" web programming library. Connect your browser to http://localhost:8080/table after starting the program. <lang oz>declare
[Roads] = {Module.link ['x-ozlib://wmeyer/roads/Roads.ozf']}
fun {Table Session}
html( head(title("Show a table with row and column headings")
style(type:"text/css" css(td 'text-align':center) ))
body(
{TagFromList table tr(th th("X") th("Y") th("Z")) | {CreateRows 3 5} })) end
fun {CreateRows NumCols NumRows}
{List.map {List.number 1 NumRows 1} fun {$ Row} {TagFromList tr
td( {Int.toString Row} ) | {List.map {List.number 1 NumCols 1} fun {$ Col} SequentialNumber = (Row-1)*NumCols + Col in td( {Int.toString SequentialNumber} ) end }}
end }
end
TagFromList = List.toTuple
in
{Roads.registerFunction table Table} {Roads.run}</lang>
PARI/GP
<lang parigp>html(n=3)={
print("\n");for(i=1,n,print1(""); for(j=1,3,print1("")); print("") ); print("
X | Y | Z | |
---|---|---|---|
"i" | "random(9999)" |
};</lang> Output:
<table> <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr> <tr><td>1</td><td>6055</td><td>6794</td><td>6034</td></tr> <tr><td>2</td><td>8930</td><td>1992</td><td>7087</td></tr> <tr><td>3</td><td>9592</td><td>5836</td><td>7980</td></tr> </table>
Note also the built-in printtex
command, which allows the analogous task to be written as
<lang parigp>printtex(matrix(4,4,i,j,if(i==1,if(j==1,"",Strchr(86+j)),if(j==1,i,random(9999)))))</lang>
Pascal
See Delphi
Perl
<lang Perl>my @heading = qw(X Y Z); my $rows = 5;
print '<thead>" } @heading),"</thead><tbody>";
for (1 .. $rows) {
print "", (map { "" } @heading), ""; } print "</tbody>', (map { " | $_ |
---|---|
$_ | ".int(rand(10000))." |
Note that this is a rather inane way (because of the inane task specification) of generating structured document. For serious work, one should use a module such as XML or HTML for well-formedness instead of this ad hoc method.
Perl 6
This is certainly not the only or best way to generate HTML tables using Perl 6; just an example of one possible method.
<lang Perl6>my @header = < X Y Z>; my $rows = 5;
sub tag ($tag, $string, $param?) { return "<$tag" ~ ($param ?? " $param" !! ) ~ ">$string" ~ "</$tag>" };
my $table = tag('tr', ( tag('th', $_) for @header));
for 1 .. $rows -> $row {
$table ~= tag('tr', ( tag('td', $row, 'align="right"') ~ (tag('td', (^10000).pick, 'align="right"') for 1..^@header)));
}
say tag('table', $table, 'cellspacing=4 style="text-align:right; border: 1px solid;"');</lang>
Sample output:
X | Y | Z | |
---|---|---|---|
1 | 2179 | 4778 | 2717 |
2 | 2160 | 1592 | 4348 |
3 | 4511 | 540 | 7187 |
4 | 3484 | 5882 | 1273 |
5 | 1310 | 4017 | 410 |
PicoLisp
<lang PicoLisp>(load "@lib/xhtml.l")
( NIL NIL '(NIL (NIL "X") (NIL "Y") (NIL "Z")) (for N 3 (<row> NIL N 124 456 789) ) )</lang>PL/I
<lang PL/I> /* Create an HTML table. 6/2011 */
create: procedure options (main);
create_table: procedure (headings, table_contents);
declare headings(*) character (10) varying; declare table_contents(*, *) fixed; declare (i, row, col) fixed;put skip edit ('
/* For an empty column heading */ do i = 1 to hbound(headings);put edit (' ' ) (a);
end;put edit ('') (a); /* Table contents. */ do row = 1 to hbound(table_contents, 1); /* row number */ put skip edit (' ') (a);
/* row contents */ do col = 1 to hbound(table_contents, 2);put edit (' ' ) (a);
end;put edit ('') (a); end; put skip edit ('
', headings(i), ' | |
---|---|
', row, ' | ', table_contents(row, col), ' |
end create_table;
declare headings (3) character (1) static initial ('X', 'Y', 'Z');
declare table_contents(3, 3) fixed static initial ( 4, -3, 8, 7, 2, -6, 11, 1, 15);
call create_table (headings, table_contents);
end create;</lang>
Protium
Opcodes of interest: SDC -- simple document; R!I -- ranged random integer
<lang html><@ SDCLIT> <@ DTBLIT> <@ DTRLITLIT> <@ DTDLITLIT>|[style]background-color:white</@> <@ DTD>X</@> <@ DTD>Y</@> <@ DTD>Z</@>|[style]width:100%; background-color:brown;color:white; text-align:center</@> <@ ITEFORLIT>10| <@ DTRLITCAP> <@ DTDPOSFORLIT>...|[style]background-color:Brown; color:white; text-align:right</@> <@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@> <@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@> <@ DTDCAPLIT><@ SAYR!ILI2>1|9999</@>|[style]width:50;text-align:right</@> |[style]background-color:white;color:black</@> </@> </@> |Number Table</@></lang>
Python
<lang python> import random
def rand9999():
return random.randint(1000, 9999)
def tag(attr=, **kwargs):
for tag, txt in kwargs.items(): return '<{tag}{attr}>{txt}</{tag}>'.format(**locals())
if __name__ == '__main__':
header = tag(tr=.join(tag(th=txt) for txt in ',X,Y,Z'.split(','))) + '\n' rows = '\n'.join(tag(tr=.join(tag(' style="font-weight: bold;"', td=i) + .join(tag(td=rand9999()) for j in range(3)))) for i in range(1, 6)) table = tag(table='\n' + header + rows + '\n') print(table)</lang>
Sample output
X | Y | Z | |
---|---|---|---|
1 | 6040 | 4697 | 7055 |
2 | 2525 | 5468 | 6901 |
3 | 8851 | 3727 | 8379 |
4 | 5313 | 4396 | 1765 |
5 | 4013 | 5924 | 6082 |
The raw HTML
<lang html5>X | Y | Z | |
---|---|---|---|
1 | 6040 | 4697 | 7055 |
2 | 2525 | 5468 | 6901 |
3 | 8851 | 3727 | 8379 |
4 | 5313 | 4396 | 1765 |
5 | 4013 | 5924 | 6082 |
Retro
Using the casket::html' library which allows creation of HTML using quotes and combinators:
<lang Retro>needs casket::html' with casket::html'
[ [ [ ] td [ "x" ] td [ "y" ] td [ "z" ] td ] tr
[ [ "1" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr [ [ "2" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr [ [ "3" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr [ [ "4" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr [ [ "5" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr [ [ "6" ] td [ rnd ] td [ rnd ] td [ rnd ] td ] tr
] table</lang>
Ruby
Pure Ruby solution:
<lang ruby> def r
rand(10000)
end
STDOUT << "".tap do |html|
html << "" [ ['X', 'Y', 'Z'], [r ,r ,r], [r ,r ,r], [r ,r ,r], [r ,r ,r] ].each_with_index do |row, index| html << "" html << "" html << row.map { |e| ""}.join html << "" end html << "#{index > 0 ? index : nil } | #{e} |
end </lang>
This creates a plain HTML table, without any CSS to draw borders or to set column widths.
<lang ruby>def r; rand(10000); end table = [["", "X", "Y", "Z"],
[ 1, r, r, r], [ 2, r, r, r], [ 3, r, r, r]]
require 'rexml/document'
xtable = REXML::Element.new("table") table.each do |row|
xrow = REXML::Element.new("tr", xtable) row.each do |cell| xcell = REXML::Element.new("td", xrow) REXML::Text.new(cell.to_s, false, xcell) end
end
formatter = REXML::Formatters::Pretty.new formatter.compact = true formatter.write(xtable, $stdout)</lang>
Output: <lang html5>X | Y | Z | |
1 | 1358 | 6488 | 6434 |
2 | 2477 | 6493 | 1330 |
3 | 240 | 3038 | 9849 |
Scheme
<lang scheme>(define table #(
#("" "X" "Y" "Z") #(1 1 2 3) #(2 4 5 6) #(3 7 8 9)))(display "") (do ((r 0 (+ r 1))) ((eq? r (vector-length table))) (display "") (do ((c 0 (+ c 1))) ((eq? c (vector-length (vector-ref table r)))) (if (eq? r 0) (display ""))) (display "")) (display "
"))
(if (> r 0)(display " | "))
(display (vector-ref (vector-ref table r) c)) (if (eq? r 0)(display "")) (if (> r 0) (display " |
---|
Seed7
<lang seed7>$ include "seed7_05.s7i";
const proc: main is func
local var integer: line is 0; var integer: column is 0; beginwriteln(""); writeln("");
for line range 1 to 3 dowrite("");
for column range 1 to 3 dowrite("");
end for;writeln(""); end for; writeln("
X | Y | Z | |
---|---|---|---|
" <& line <& " | " <& rand(0, 9999) <& " |
end func;</lang>
Output:
<table style="text-align:center; border: 1px solid"> <tr><th></th><th>X</th><th>Y</th><th>Z</th></tr> <tr><th>1</th><td>9682</td><td>2439</td><td>7698</td></tr> <tr><th>2</th><td>2958</td><td>4336</td><td>8340</td></tr> <tr><th>3</th><td>6245</td><td>6544</td><td>457</td></tr> </table>
Output viewed with a browser:
X | Y | Z | |
---|---|---|---|
1 | 9682 | 2439 | 7698 |
2 | 2958 | 4336 | 8340 |
3 | 6245 | 6544 | 457 |
Tcl
<lang tcl># Make ourselves a very simple templating lib; just two commands proc TAG {name args} {
set body [lindex $args end] set result "<$name" foreach {t v} [lrange $args 0 end-1] {
append result " $t=\"" $v "\""
} append result ">" [string trim [uplevel 1 [list subst $body]]] "</$name>"
} proc FOREACH {var lst str} {
upvar 1 $var v set result {} set s [list subst $str] foreach v $lst {append result [string trim [uplevel 1 $s]]} return $result
}
set titles {"" "X" "Y" "Z"} set data {} for {set x 0} {$x < 4} {incr x} {
# Inspired by the Go solution, but with extra arbitrary digits to show 4-char wide values lappend data [list \
[expr {$x+1}] [expr {$x*3010}] [expr {$x*3+1298}] [expr {$x*2579+2182}]] }
puts [TAG table border 1 {
[TAG tr bgcolor #f0f0f0 {
[FOREACH head $titles { [TAG th {$head}] }]
}] [FOREACH row $data {
[TAG tr bgcolor #ffffff { [FOREACH col $row { [TAG td align right {$col}] }] }]
}]
}]</lang>
TUSCRIPT
<lang tuscript> $$ MODE TUSCRIPT tablefile="table.html" ERROR/STOP CREATE (tablefile,FDF-o,-std-) ACCESS d: WRITE/ERASE/RECORDS/utf8 $tablefile s,tablecontent tablecontent=* WRITE d "<!DOCTYPE html system>" WRITE d "<html><head><title>create html table</title></head>"
WRITE d "<body><thead align='right'>" WRITE d ""WRITE d "</thead>" WRITE d "<tbody align='right'>" LOOP n=1,5 x=RANDOM_NUMBERS (1,9999,1) y=RANDOM_NUMBERS (1,9999,1) z=RANDOM_NUMBERS (1,9999,1)
WRITE d ""ENDLOOP
WRITE d "</tbody>x | y | z | |
---|---|---|---|
{n} | {x} | {y} | {z} |
ENDACCESS d BROWSE $tablefile </lang> Output:
<!DOCTYPE html system> <html><head><title>create html table</title></head> <body><table><thead align='right'> <tr><th> </th><th>x</th><th>y</th><th>z</th></tr> </thead> <tbody align='right'> <tr><td>1</td><td>268</td><td>2409</td><td>8627</td></tr> <tr><td>2</td><td>2095</td><td>1455</td><td>269</td></tr> <tr><td>3</td><td>3763</td><td>9225</td><td>1957</td></tr> <tr><td>4</td><td>1304</td><td>9434</td><td>2208</td></tr> <tr><td>5</td><td>3547</td><td>4051</td><td>4859</td></tr> </tbody></table></body></html>
VBA
<lang VBA> Public Sub BuildHTMLTable() 'simple HTML table, represented as a string matrix "cells" Const nRows = 6 Const nCols = 4 Dim cells(1 To nRows, 1 To nCols) As String Dim HTML As String 'the HTML table Dim temp As String Dim attr As String
' fill table ' first row with titles cells(1, 1) = "" cells(1, 2) = "X" cells(1, 3) = "Y" cells(1, 4) = "Z" 'next rows with index & random numbers For i = 2 To nRows
cells(i, 1) = Format$(i - 1) For j = 2 To nCols cells(i, j) = Format$(Int(Rnd() * 10000)) Next j
Next i
'build the HTML HTML = "" For i = 1 To nRows
temp = "" 'first row as header row If i = 1 Then attr = "th" Else attr = "td" For j = 1 To nCols temp = temp & HTMLWrap(cells(i, j), attr) Next j HTML = HTML & HTMLWrap(temp, "tr")
Next i HTML = HTMLWrap(HTML, "table", "style=""text-align:center; border: 1px solid""") Debug.Print HTML End Sub
Public Function HTMLWrap(s As String, tag As String, ParamArray attributes()) As String
'returns string s wrapped in HTML tag with optional "attribute=value" strings 'ex.: HTMLWrap("Link text", "a", "href=""http://www.somesite.org""") 'returns: <a href="http://www.somesite.org">Link text</a> Dim sOpenTag As String Dim sClosingTag As String
sOpenTag = "<" & tag For Each attr In attributes sOpenTag = sOpenTag & " " & attr Next sOpenTag = sOpenTag & ">" sClosingTag = "</" & tag & ">" HTMLWrap = sOpenTag & s & sClosingTag
End Function </lang>
Subroutine BuildHTMLTable builds the HTML code as one big string. Sample output of call to BuildHMTLTable:
<table style="text-align:center; border: 1px solid"><tr><th></th><th>X</th><th>Y</th><th>Z</th></tr><tr><td>1</td><td>1906</td><td>6840</td><td>7474</td></tr><tr><td>2</td><td>6139</td><td>7821</td><td>1617</td></tr><tr><td>3</td><td>8077</td><td>2026</td><td>9567</td></tr><tr><td>4</td><td>658</td><td>615</td><td>7931</td></tr><tr><td>5</td><td>3796</td><td>4635</td><td>1195</td></tr></table>
which corresponds to:
X | Y | Z | |
---|---|---|---|
1 | 1906 | 6840 | 7474 |
2 | 6139 | 7821 | 1617 |
3 | 8077 | 2026 | 9567 |
4 | 658 | 615 | 7931 |
5 | 3796 | 4635 | 1195 |
- Programming Tasks
- Solutions by Programming Task
- HTML
- Ada
- AutoHotkey
- AWK
- BBC BASIC
- C
- C++
- C sharp
- CoffeeScript
- D
- Delphi
- Euphoria
- Go
- Icon
- Unicon
- Icon Programming Library
- J
- Java
- JavaScript
- Liberty BASIC
- Mathematica
- MATLAB
- Octave
- Modula-2
- NewLISP
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PicoLisp
- PL/I
- Protium
- Python
- Retro
- Ruby
- REXML
- Scheme
- Seed7
- Tcl
- TUSCRIPT
- VBA