How to get an $m\times n$ matrix with distinct rows that have $n=\frac{m}{3}$ different letters per row I want to fill a matrix with $m$ rows and $n$ colums where $m\geq 12$ and $4\leq n\leq 26$ and $n=\frac{m}{3}$.
Let $(i,j)$ denote the i-th row and the j-th column. At $(i,j)$ I want to put a letter $\underbrace{A,B,\ldots}_{n~\mathrm{letters}}$. So if $n=4$ use the letters $A,B,C,D$.
Each row must have n distinct letters and each letter must appear exactly 3 times in each column.
I prefer to implement this in R. How can I do this? I want to use this for a matching problem with a graph. The input troubles me, if I get the input of the matrix correct, I can use a ready-made subroutine to solve my problem.
 A: This relates closely to experimental design.
If it is necessary for all the rows to be distinct, you'll could look at getting three mutually orthogonal Latin squares and stacking them one on top of the other. In some cases that trick will not give you a solution, such as when $n=6$.
However, there are designs with all rows distinct that are not mutually orthogonal:
ABCDEF
BCDEFA
CDEFAB
DEFABC
EFABCD
FABCDE

AFECDB
BEAFCD
CDBEAF
DCFABE
EBCDFA
FADBEC

ADEBFC
BFCADE
CADEBF
DEBFCA
EBFCAD
FCADEB

So that would seem to solve the n=6 problem even though no pair of order 6 Latin squares are orthogonal (your problem simply requires distinct rows which is less restrictive)

Actually, here's an algorithm that seems to fulfill your criteria:


*

*write the symbols "$A$","$B$",...,$S_n$ (where $S_n$ is the $n$-th symbol) to form the first row

*cycle through the values to form the next  $n-1$ rows, so row 2 is "$B$","$C$",...,$S_n$,"$A$"

*start a new block of $n$ by writing the first row starting with "$A$", but then cycle the remaining $n-1$ symbols, so you get "$A$","$C$","$D$",...,$S_n$,"$B$"

*continue the second block in the same way as the first block by cycling the whole first row

*start the third block of $n$ by again starting with "$A$", but cycle the remaining $n-1$ symbols from the first row of the second block, which gives "$A$","$D$",...,$S_n$,"$B$","$C$"

*Cycle through that new order of $n$ symbols until all $n$ rows of the 3rd block are filled.
For the n=4 case this gives:
ABCD
BCDA
CDAB
DABC

ACDB
CDBA
DBAC
BACD

ADBC
DBCA
BCAD
CADB

