TransWikia.com

Rectangular table with consecutive integers using foreach

TeX - LaTeX Asked by Péter Juhász on August 5, 2021

I’d like to have a rectangular table with integers (like a lottery ticket), let’s say 4×9, numbers from 1 to 36.
I assumed that it is easy with tikz, two foreach loops. Like this:

foreach i in {0,1,2,...,8}{
  foreach j in {1,2,3,4}{
    draw[fill=blue!15] (i,j) rectangle (1+i,1+j);
    tikzmath{k=9*(4-j)+i+1;} 
    draw (i+0.5,j+.5) node {k};
  }
}

But the numbers have the form 1.0, 2.0, etc, but I’d like to have 1, 2, etc.
Could you help me?

3 Answers

pgfmathprintnumber solves the problem.

I really don't know why this is so complicated.

Answered by Péter Juhász on August 5, 2021

Here's a LuaLaTeX-based solution. It employs two for loops.

enter image description here

documentclass{article}
usepackage{array}   % for extrarowheight length parameter and 'w' column type
usepackage{luacode} % for luaexec macro
begin{document}

setlengthextrarowheight{2pt} % make squares 14pt wide and tall
setlengthtabcolsep{4pt}

begin{tabular}{|*{9}{w{c}{6pt}|}}
hline
luaexec{
  for i=1,4 do
    for j=1,8 do 
      tex.sprint( i*j .. "&" ) 
    end
    tex.sprint( i*9 .. "\ hline" )
  end }
end{tabular}
end{document}

Answered by Mico on August 5, 2021

documentclass[tikz, border=2mm]{standalone}

begin{document}

begin{tikzpicture}
foreach i in {0,1,2,...,8}{
  foreach j [evaluate=j as num using int(9*(4-j)+i+1)] in {1,2,3,4}
    node[fill=blue!15, minimum size=1cm, draw] at (i,j) {num};
}
end{tikzpicture}

end{document}

enter image description here

Answered by Ignasi on August 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP