MATLAB: Create matrix (30 x 12) with numbers from 1 to 12 without repetition without any repetitions of following numbers for each row

permuterepetition

Hi all,
I want to create a matrix (30 rows, 12 columns) with numbers from 1 to 12. Each row should be as unique as possible, so that two numbers are barely following each other.
For example:
11 3 8 9 12 4 10 5 1 7 6 2
6 7 5 1 4 9 12 3 8 2 11 10
In this case of only 2 rows 8 follows 3 and 12 follows 9. This is what I want to avoid.
Can anyone help me out?
Thanks in advance!

Best Answer

here the solution:
A=randperm(12);
iterac=500;
for k=1:30-1
it=0;
while true
it=it+1;
b=randperm(12);
c2=[diff(b); b(1:end-1) .* b(2:end)];
cd=0;
for j=1:size(A,1)
c=[diff(A(j,:)); A(j,1:end-1) .* A(j,2:end)];
if size(intersect(c',c2','rows'),1)<=1 || (size(intersect(c',c2','rows'),1)<=2 && it>iterac)
cd=cd+1;
end
end
if cd==size(A,1)
A(end+1,:)=b;
break
end
end
end
disp(A)