How can I generate a vector of 19 numbers in such a way that all 19 numbers are repeated 10 times, but 10 consecutive numbers are not equal?

1 次查看(过去 30 天)
So far, the code I have is this:
nTargs = 19;
pairs = nchoosek(1:nTargs, 10);
nPairs = size(pairs, 1);
order = randperm(nPairs);
values=randsample(order,19);
targs=pairs(values,:);
Alltargs=false;
while ~Alltargs
targs=pairs(randsample(order,19),:);
B=[];
for i=1:19
G=length(find(targs==i))==10;
B=[B G];
end
if sum(B)==19
Alltargs=true;
end
end
The computation time was a huge issue, there has to be a nicer way to do this. I also thought about generating all of the values and then doing some sort of rearrangement, but that was not fruitful. Code for that is below
N=[];
for i=1:10
N=[N randperm(19)];
end
B=[];
for j=1:19
if length(unique(N(j*10-9:j*10)))<10
B=[B 1];
end
end
B
Thanks for any input.
  2 个评论
Walter Roberson
Walter Roberson 2014-2-4
编辑:Walter Roberson 2014-2-4
When you say "but 10 consecutive numbers are not equal", do you mean that no sequence of 10 digits is exactly the same as any other sequence of 10 digits, or do you mean that in every sequence of 10 digits, no digit is repeated?

请先登录,再进行评论。

采纳的回答

Niklas Nylén
Niklas Nylén 2014-2-4
编辑:Niklas Nylén 2014-2-4
My suggestion is to start with any valid vector according to your constraints. In the example below I have chosen the most obvious one which is 1,2,3,...,18,19,1,2,...
The next step is to move around the numbers in a way that always will end up with a valid vector but still introduces some randomness. One way to do that is to take a random index and switch place with its neighbor, if the move results in a vector which fulfills the constraints. Since we know that the old vector is valid it is only necessary to check exactly +- 10 indexes from the random position.
y = repmat(1:19,1,10);
% Run enough iterations to get the output random enough, I selected 100000
for ii = 1:100000
% Select random index
index = randi(length(y)-1);
% Check if it is allowed to switch places
if y(index)~=y(min(index+10, length(y))) && y(index+1)~=y(max(1,index-9))
% Make the switch
yTmp = y(index);
y(index)=y(index+1);
y(index+1)=yTmp;
end
end
My code runs in ~0.5 s with 100 000 iterations, of which approximately 85 000 result in a valid move.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by