22
\$\begingroup\$

Input :

Two decimal integers m and n that respectively give the number of rows and columns of the table. m and n are greater than or equal to 1.

Output :

A table in HTML that has m rows and n columns.

The table should be displayable by a modern browser of your choice. Most browsers will display everything properly even if tags are not closed. Proper indentation and spacing is optional.

There should be at least one (non-whitespace) printable character in each cell.

Cells on the first line should use <th> tags while the ones on the following lines should use <td>tags.

Win condition :

This is so the shortest source-code for each language wins.

Input example :

2 3

Output example :

<table>
 <tr>
   <th>A</th>
   <th>A</th>
   <th>A</th>
 </tr>
 <tr>
   <td>A</td>
   <td>A</td>
   <td>A</td>
 </tr>
</table>

or : <table><tr><th>A<th>A<th>A<tr><td>A<td>A<td>A

\$\endgroup\$
  • \$\begingroup\$ Comments are not for extended discussion; this conversation has been moved to chat. \$\endgroup\$ – Mego May 9 '18 at 13:21

30 Answers 30

7
\$\begingroup\$

APL (Dyalog Unicode) with MiServer 3.0, 31 30 bytesSBCS

Full program. Prompts stdin for the two-element list [m,n] and prints strict XHTML to stdout.

(⎕NEW _.Table((⎕⍴0)⍬1)).Render

Example session:

      )xload C:\Users\Adam.DYALOG\Documents\MiServer\miserver.dws
C:\Users\Adam.DYALOG\Documents\MiServer\miserver.dws saved Wed Mar  7 17:19:40 2018
      Load ''
Development environment loaded
MiSite "C:/Users/Adam.DYALOG/Documents/MiServer/MS3/" loaded
      (⎕NEW _.Table((⎕⍴0)⍬1)).Render
⎕:
      2 3
<table id="id691498143"><thead><tr><th>0</th><th>0</th><th>0</th></tr></thead><tbody><tr><td>0</td><td>0</td><td>0</td></tr></tbody></table>

Try it online!

Explanation:

().Render Render the following HTML element:

⎕NEW _.Table () a new Table with the following parameters:

  () ⍬ 1 the following content, no special styling, 1 header row:

   ⎕⍴0 evaluated input reshapes zero (i.e. an m-row, n-column matrix of zeros)

\$\endgroup\$
6
\$\begingroup\$

JavaScript (ES6), 70 bytes

Saved 2 bytes thanks to @RickHitchcock

Takes input in currying syntax (m)(n).

m=>n=>'<table>'+(g=c=>'<tr>'+`<t${c}>A`.repeat(n))`h`+g`d`.repeat(m-1)

Try it online!

Demo

f=

m=>n=>'<table>'+(g=c=>'<tr>'+`<t${c}>A`.repeat(n))`h`+g`d`.repeat(m-1)

O.innerHTML = f(2)(3)
<div id=O></div>

\$\endgroup\$
5
\$\begingroup\$

Python 2, 57 bytes

lambda m,n:'<table><tr>'+'<th>A'*n+('<tr>'+'<td>A'*n)*~-m

Try it online! Assumes m isn't zero.

\$\endgroup\$
5
\$\begingroup\$

Canvas, 31 bytes

<ŗ>
table⁸o╶[tr⁸⁶{¹1≡╵dh@t×⁸;}]

Try it here! or Try it visualized!

After fixing 2 bugs (ಠ_ಠ) in the interpreter, 30 bytes works too

\$\endgroup\$
3
\$\begingroup\$

JavaScript, 65 bytes

f=(m,n)=>m?f(--m,n)+'<tr>'+`<t${m?'d':'h'}>x`.repeat(n):'<table>'

document.write(f(4,3));

\$\endgroup\$
  • \$\begingroup\$ recursion. nice! \$\endgroup\$ – mazzy Jun 10 '18 at 9:01
2
\$\begingroup\$

05AB1E, 30 bytes

’<…È>’sF"<tr>"„hdNĀè"<tÿ>A"I×J

Try it online!

Explanation

’<…È>’                           # push "<table>"
      sF                         # no-of-rows times do:
        "<tr>"                   # push "<tr>"
              „hd                # push "hd"
                 NĀ              # push the iteration counter truthified
                   è             # index into the 2-char string with this
                    "<tÿ>A"      # insert the result into the string "<tÿ>A" instead of ÿ
                           I×    # repeat this string no-of-columns times
                             J   # join the stack to a single string
\$\endgroup\$
2
\$\begingroup\$

Stax, 28 bytes

üÉ$♠═?S┼╪├8°‼←sí☼←T≡┴╜ô‼\↑0ⁿ

Run and debug it

Unpacked, ungolfed, and commented, it looks like this.

"<table>"P  print "table"
"<th>A"*    "<th>A" repeated specified number of times
,D          repeat the rest of the program specified number of times
  "<tr>"p   print "<tr>" with no newline
  Q         print top of stack without popping
  .hd|t     replace "h" with "d"

Run this one

\$\endgroup\$
2
\$\begingroup\$

Java 10, 139 133 102 bytes

m->n->{var r="<table>";for(int j=0,i;j++<m;)for(r+="<tr>",i=n;i-->0;r+=j<2?"<th>A":"<td>B");return r;}

Try it online.

Explanation:

n->m->{                  // Method with two integer parameters and String return-type
  var r="<table>";       //  Result-String, starting at "<table>"
  for(int j=0,i;j++<m;)  //  Loop `j` over the rows in the range [0, `m`)
    for(r+="<tr>",       //   Append "<tr>" to the result
        i=n;i-->0;       //   Inner loop `i` over the columns in the range [`n`, 0)
      r+=j<2?            //    If `j` is 1 (first iteration):
          "<th>A"        //     Append "<th>A" to the result
         :               //    Else:
          "<td>B");      //     Append "<td>B" to the result
  return r;}             //  Return the result
\$\endgroup\$
  • \$\begingroup\$ I think there's a little typo, you wrote "th" twice. \$\endgroup\$ – potato May 7 '18 at 17:44
  • \$\begingroup\$ @potato Ah, you're right. The code itself and the TIO-link were correct, but my explanation had a typo. Should be fixed now, thanks. \$\endgroup\$ – Kevin Cruijssen May 8 '18 at 6:50
  • \$\begingroup\$ (m,n)->{var l="<tr>";for(;n-->0;)l+="<td>A";var s="<table>"+l.replace('d','h');for(;--m>0;)s+=l;return s;} (106 bytes) I found this one interesting, but not worth it given your current score. You probably can golf a bit your answer using ideas here like the mutable m. \$\endgroup\$ – Olivier Grégoire May 8 '18 at 9:24
  • \$\begingroup\$ @OlivierGrégoire I initially had a modifiable m, but due to the <th>/<td> differences it wouldn't matter. I still need to check whether it's the first iteration of the outer loop, in which case I need both j and m, and I need to do the inner loop multiple times, in which case I need i and n. Instead of going upwards from 0 and checking j<2 I could go backwards and check i>m-2, but it would be +1 byte instead of -1. Your approach of using two separated loops with modifiable m and n is indeed interesting, though. :) \$\endgroup\$ – Kevin Cruijssen May 8 '18 at 9:37
2
\$\begingroup\$

APL (Dyalog Unicode), 42 38 bytesSBCS

-4 thanks to ngn.

Full program. Prompts stdin for the two-element list [m,n] and prints unclosed tags to stdout.

'<table>',∊'<tr>',⍤1{'d'}@3⍀⎕⍴⊂'<th>A'

Try it online!

⊂'<th>A' enclose this string to treat it as a whole

⎕⍴ prompt for dimensions and cyclically reshape the single cell to a matrix of that size

…⍀ cumulatively insert the following function between each vertical pair of cells:

{'d'}@3 ignore upper cell; place d at 3rd position in bottom cell

'<tr>',⍤1 prepend this string each row

ϵnlist (flatten)

'<table>', prepend this string

\$\endgroup\$
2
\$\begingroup\$

C (gcc), 107 99 98 97 bytes

i;f(x,y){char s[]="<th>A";for(puts("<table><tr>");x--;s[2]=96+puts("<tr>"))for(i=y;i--;)puts(s);}

Try it online!

-8 bytes thanks to potato

-2 bytes thanks to ceilingcat

The s array has to be declared as an array not a pointer otherwise it won't be editable (we set the first h to a d). Most browsers don't even care if your closing tag is correct, so we just close all tags with </t>.

\$\endgroup\$
  • \$\begingroup\$ Still works fine if you remove the </t> that appears twice and -8 bytes. \$\endgroup\$ – potato May 7 '18 at 17:48
  • \$\begingroup\$ You can shave 4 more bytes off if you move outputting the new row to the inner loop (also, it avoids an empty row): Try it online! \$\endgroup\$ – ErikF May 8 '18 at 22:58
2
\$\begingroup\$

R, 73 bytes

function(n,m)cat("<table><tr>","<th>A"<m,c("<tr>","<td>A"<m)<n-1)
"<"=rep

Try it online!

Saved 7 bytes with a dirty hack - replace "rep" by "<".

\$\endgroup\$
1
\$\begingroup\$

Haskell, 109 107 103 bytes

n!i="<t"++n++'>':i++"</t"++n++">"
r#c="able"!("r"!([1..c]*>"h"!"H")++([2..r]*>("r"!([1..c]*>"d"!"A"))))

So many parentheses… Thanks to @nimi for two bytes (and a loss of genericity)!

Try it online!

Without end tags the straight implementation wins at 87 bytes (Try it online):

r?c="<table><tr>"++([1..c]*>"<th>H")++([2..r]*>("<tr>"++([1..c]*>"<td>A")))++"</table>"
\$\endgroup\$
1
\$\begingroup\$

APL+WIN, 68 63 56 bytes

12 bytes in total saved thanks to Adám

Prompts for number of rows followed by number of columns and outputs non-closure option:

t←⊂'<tr>'⋄'<table>'t(n⍴⊂'<th>A'),,t,((⎕-1),n←⎕)⍴⊂'<td>A'
\$\endgroup\$
  • \$\begingroup\$ @Adám Too trigger happy I am afraid. Looks OK now? \$\endgroup\$ – Graham May 7 '18 at 15:47
  • \$\begingroup\$ Yes, but you don't need the or the trailing parens: t,,((⎕-1),n←⎕)⍴r or the first two commas. \$\endgroup\$ – Adám May 7 '18 at 15:48
  • \$\begingroup\$ @Adám Thanks. Its not my day must be the heat (28C)! \$\endgroup\$ – Graham May 7 '18 at 16:01
  • \$\begingroup\$ Merge h and r into the main expression: '<table>'t(n⍴⊂'<th>A')t,,((⎕-1),n←⎕)⍴⊂'<td>A' \$\endgroup\$ – Adám May 7 '18 at 16:34
  • \$\begingroup\$ Something isn't right. You only insert one <tr> for the body. Each row needs a <tr>. \$\endgroup\$ – Adám May 7 '18 at 16:36
1
\$\begingroup\$

Retina, 56 54 bytes

(.+) (.+)
<table>$1*$(<tr>$2*$(<td>@
T`\d`\h`^.*?r.*?r

Try it online! Edit: Saved 2 bytes thanks to @CowsQuack. Explanation: The first stage uses Retina 1's string multiplication first to generate the appropriate number of cells, then to generate the appropriate number of rows. The second stage then changes the first row of tds into ths.

\$\endgroup\$
  • \$\begingroup\$ If you know the input is going to be split by spaces, then you should be able to use . instead of \d \$\endgroup\$ – Kritixi Lithos May 7 '18 at 18:19
1
\$\begingroup\$

Charcoal, 33 bytes

<table><tr>×<th>AηF⊖θ«<tr>×<td>Aη

Try it online!

Explanation

<table><tr>                         Print "<table><tr>"
           ×<th>Aη                  Print "<th>A" * second input
                  F⊖θ«            For i in (implicit) range over first input
                        <tr>        Print("<tr>")
                            ×<td>Aη Print("<td>A") * second input
\$\endgroup\$
1
\$\begingroup\$

K, 58 bytes

K version is whatever is included in KDB+ 3.5 2017.11.30.

Port of the Python answer above. Ends up being 1 byte longer due to having to enlist and flatten multiple times.

{,/"<table><tr>",(y#,"<th>A"),(x-1)#,("<tr>",/y#,"<td>A")}
\$\endgroup\$
1
\$\begingroup\$

Perl 5 -p, 65 54 bytes

-11 bytes thanks to @msh2108's reminder

/ /;$_="<table><tr>"."<th>A"x$'.('<tr>'.'<td>B'x$')x$`

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Save yourself some bytes. Per an example in the challenge, you can drop the .'</table>'. \$\endgroup\$ – msh210 May 8 '18 at 8:03
1
\$\begingroup\$

C# (.NET Core), 130 bytes

m=>n=>{var r="<table>";for(int i=0;i++<m;)r+="<tr>"+string.Concat(System.Linq.Enumerable.Repeat(i<2?"<th>H":"<td>D",n));return r;}

Try it online!

\$\endgroup\$
1
\$\begingroup\$

PowerShell Core, 72 68 bytes

Function F($m,$n){'<table><tr>'+'<th>A'*$n+('<tr>'+'<td>A'*$n)*--$m}

Try it online!

Here are my test cases and expected outputs (C.f., TIO)

  • m=2; n=3 <table><tr><th>A<th>A<th>A<tr><td>A<td>A<td>A
  • m=1; n=3 <table><tr><th>A<th>A<th>A
  • m=4; n=2 <table><tr><th>A<th>A<tr><td>A<td>A<tr><td>A<td>A<tr><td>A<td>A
  • m=2; n=8 <table><tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A

Thanks, @mazzy, for the -4 bytes!

\$\endgroup\$
  • 1
    \$\begingroup\$ Brackets are optional. Try Function F($m,$n){'<table><tr>'+'<th>A'*$n+('<tr>'+'<td>A'*$n)*--$m}. \$\endgroup\$ – mazzy Jun 10 '18 at 6:58
0
\$\begingroup\$

Pyth, 40 bytes

J"<tr>"AQ"<table>"J*H"<th>A"*tGJ*H"<td>A

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Dart, 45 63 bytes

Working solution:

(m,n){print('<table><tr>'+'<th>A'*n+('<tr>'+'<td>A'*n)*(m-1));}

Try it online here!

Lambda/anonymous function taking m and n as parameters, displays output to STDOUT.

Since tables with unclosed <table>, <tr>, <th>, and <td> tags still render in modern browsers (ex., Chrome), the output is valid.

Old (broken) solution:

My first attempt forgot to switch to <td> after the first row:

(m,n){print('<table><tr>'+'<th>A'*n+('<tr>'+'<th>A'*n)*(m-1));}

Thanks to @Lynn for pointing that out.

\$\endgroup\$
0
\$\begingroup\$

Google Sheets, 66 bytes

="<table><tr>"&Rept("<th>A",B1)&Rept("<tr>"&Rept("<td>A",B1),A1-1)

Input is in cell A1 and B1.
There's nothing fancy, really; it's just nested Rept functions.
It does assume m > n > 0 and that they're both integers.

\$\endgroup\$
0
\$\begingroup\$

Jelly,  33  32 bytes

“<td>A”ẋ”h3¦s5ẋ€ṭ€“<tr>”ṭ“¢ssɱU»

A full program taking rows, columns which prints the result.

Try it online!


hmm, also 32 using a table:

Ịị⁾hdṭ”t⁾<>j;ðþZṭ€“<tr>”ṭ“¢ssɱU»
\$\endgroup\$
0
\$\begingroup\$

J, 64 bytes

Another port of the Python answer:

4 :0
'<table><tr>',(;y#<'<th>A'),;(<:x)#<('<tr>',(;y#<'<td>A'))
)
\$\endgroup\$
0
\$\begingroup\$

PHP, 161 Bytes

Try it online

Code

function f($m,$n){$t=["table>","th>","td>","tr>","</"];echo strtr("
<0<3".str_repeat("<1A41",$n)."43".str_repeat("<3".str_repeat("
<2A42",$n)."43",$m-1)."40",$t);}

Explanation

function f($m,$n){
  $t=["table>","th>","td>","tr>","</"];           //array representing the tags its created
  echo strtr("<0<3".str_repeat("<1A41",$n)."43"   //strtr it's called and uses 
                                                  //the array to replace values
           .str_repeat("<3".                      //repeat the tags
                         str_repeat("<2A42",$n)   //repeat the tags again
                            ."43",$m-1)."40",$t); 
   //its repeated m-1 times because head is counted as one row
  }

PHP, 193 Bytes

Full table structure forgot <tfooter> <thead>, <tbody>..etc..

Try example of the function

function f($m,$n)   {$t=["table>","thead>","tbody>","th>","td>","tbody>","tr>"];
echo strtr(
      "<0<1".str_repeat("<3A</3",$n).
      "</1<2".str_repeat(
                  "<6".str_repeat("<4A</4",$n)
                       ."</6",$m-1)."</2</0",
  $t);
  }

Explanation

$t=["table>","thead>","tbody>","th>","td>","tbody>","tr>"];

An array with all the tags for the table it's builded and then with str_repeat a number refering to an index in the array is written, then to strtr the string plus the array is passed

\$\endgroup\$
0
\$\begingroup\$

Yabasic, 124 bytes

An anonymous function that takes input from as space delimited integers and outputs to the console.

?"<table>"
input""i,j
For c=1To i
?"<tr>"
For r=1To j
If c=1?"<th>H</th>"
If c>1?"<td>D</td>"
Next
?"</tr>"
Next
?"</table>"

Try it online!

\$\endgroup\$
  • \$\begingroup\$ This doesn't produce the <td> tags. \$\endgroup\$ – potato May 17 '18 at 7:53
  • \$\begingroup\$ @potato - ahh, I hadn't seen that. It's corrected. \$\endgroup\$ – Taylor Scott May 17 '18 at 10:32
0
\$\begingroup\$

Forth (gforth), 86 bytes

: f ." <table>" 0 do ." <tr>" dup 0 do j if ." <td>A" else ." <th>A" then loop loop ; 

Try it online!

Explanation

." <table>"         \ output <table>
0 do                \ start loop from 0 to m-1
   ." <tr>"         \ output <tr>
   dup 0 do         \ duplicate n and loop from 0 to n-1
      j if          \ if the outer loop index is true (not 0)
         ." <td>A"  \ output <td>A
      else          \ if outer loop index is false (0)
         ." <th>A"  \ output <th>A
      then          \ end if-else
   loop             \ end inner loop
loop                \ end outer loop                      
\$\endgroup\$
0
\$\begingroup\$

Carrot, 77 51 bytes

<th>A^*$v<tr>vl+(^h)*($^F- 1)A"h"S"d"h+(^l)v<table>

(While working on this, I discovered a bug with h not working and fixed it)

Golfed some bytes by shortening the html as well as using "split, join" instead of "replace"

Try it online!, use the command-line option -d to see the AST (Note: this uses the new node interpreter, so the older version on the website cannot run this.)

This program takes the input 0-indexed and in reversed order, because of Carrot's weird nature, thus 3 2 printing a 3×4 table.

Run the program like so, ./carrot -f prog.carrot input.txt

Basically creates the header row, then the data rows on another cell of the garden (2D tape), and concatenates them together.


Carrot works on a 2D tape, called a garden. Each cell on the garden is made up of three stack modes, string, float, array. There is a value for each mode, called a "stack" (note: misnomer). These stacks begin empty. When a cell is at a particular mode, the following commands will affect the stack that corresponds to this mode, for example in float mode, the operations will affect the stack float. And of course, there are commands for switching between modes. The modes are important because each operator can be overloaded for each mode and each argument type.

In addition, there are two additional modes (these only affect the commands, not the stack directly), normal mode and caret mode. Normal mode works normally, where there are operators taking in arguments and affecting the stack directly. In caret mode, (almost) every character is interpreted literally as a string, and is later prepended/appended accordingly to the stack. Caret mode is started/ended with carets (append) or down-carets (prepend).

Carrot begins in a cell on the garden, in stack-string mode, and in caret mode.


Beginning in caret-mode, the string <th>A is added to the initially empty stack-string. Then follows the * command that duplicates it $, the input, times. Then <tr> is prepended to the stack-string by the usage of the down-caret v. This creates the header row of the table.

To create the data rows, we duplicate the header to another cell. l moves the IP to the right empty cell, and + appends (^h) the string in the cell to the left (essentially copying it to the cell on the right). () starts a subshell, a new Carrot program with almost the same tape, and ^ exits out of caret-mode so that we can h get the string in the left cell. This is then * duplicated by ($^F- 1), the next input minus 1, times.

Still in the right cell, A sets the array of this cell to its stack- tring split by "h". S joins the stack array by "d" and sets the stack string to this value. A"h"S"d" really just replaces hs with ds to form the data rows. Now h we move to the left starting cell.

Now we append the stack string of the cell to the right to this cell using +(^l). All that's remaining is to add the <table> tag, so we do this by v prepending it.

\$\endgroup\$
0
\$\begingroup\$

K (ngn/k), 51 bytes

{"<table>",/"<tr>",//:y#'(,,"<th>A"),1_x#,,"<td>A"}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Powershell, 63 bytes

$m,$n=$args;$t='h';'<table>';1..$m|%{'<tr>'+"<t$t>A"*$n;$t='d'}

save it as new-mntable.ps1. Test script:

.\new-mntable.ps1 2 3
.\new-mntable.ps1 1 3
.\new-mntable.ps1 4 2
.\new-mntable.ps1 2 8

output (extra spaces are optional):

<table>
<tr><th>A<th>A<th>A
<tr><td>A<td>A<td>A
<table>
<tr><th>A<th>A<th>A
<table>
<tr><th>A<th>A
<tr><td>A<td>A
<tr><td>A<td>A
<tr><td>A<td>A
<table>
<tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A
<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A

Powershell, 65 bytes, -replace

'<table>h'+'d'*--$args[0]-replace'h|d',('<tr>'+'<t$0>A'*$args[1])

save it as new-mntable.ps1. Test script:

.\new-mntable.ps1 2 3
.\new-mntable.ps1 1 3
.\new-mntable.ps1 4 2
.\new-mntable.ps1 2 8

output:

<table><tr><th>A<th>A<th>A<tr><td>A<td>A<td>A
<table><tr><th>A<th>A<th>A
<table><tr><th>A<th>A<tr><td>A<td>A<tr><td>A<td>A<tr><td>A<td>A
<table><tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A

How it work:

  1. '<table>h'+'d'*--$args[0] - create a string like <table>hddd...
  2. 'h|d'- search h or d chars in the string for replacing
  3. '<tr>'+'<t$0>A'*$args[1] - replace each char with string like <tr><t$0>A<t$0>A...
  4. where $0 is a captured group[0] - the char in the -replace.

Powershell, 65 bytes, scriptblock

$m,$n=$args;'<table>';&($r={'<tr>'+"<t$args>A"*$n})h;(&$r d)*--$m

save it as new-mntable.ps1. Test script:

.\new-mntable.ps1 2 3
.\new-mntable.ps1 1 3
.\new-mntable.ps1 4 2
.\new-mntable.ps1 2 8

output:

<table>
<tr><th>A<th>A<th>A
<tr><td>A<td>A<td>A
<table>
<tr><th>A<th>A<th>A

<table>
<tr><th>A<th>A
<tr><td>A<td>A<tr><td>A<td>A<tr><td>A<td>A
<table>
<tr><th>A<th>A<th>A<th>A<th>A<th>A<th>A<th>A
<tr><td>A<td>A<td>A<td>A<td>A<td>A<td>A<td>A
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.