Rearrange randomly just some parts of an array

1 回表示 (過去 30 日間)
luca
luca 2019 年 10 月 3 日
コメント済み: Andrei Bobrov 2019 年 10 月 8 日
Given
C = [1 2 1 2 1 2 1 2 4 2 4 2 4 2 4 2 6 2 6 2 6 7 6 7 6 7 6 7 7 7 7 7 8 8 8 8 9 9 9 9 ]
I want to rearrange randomly just some subset of the array C where I have maximum two diversity of elements. It means for example that I want to mix 1 and 2 till I meet 4.
Let's see an image in order to well understand what I want to do
A subset ends when a third diversity is met
Then in each subset I want to ranperm the value in order to rearrange randomly the elements inside,
obtaining for example
R = [1 1 2 2 1 1 2 2 4 4 2 2 4 2 4 2 2 6 6 2 6 7 7 6 7 7 6 7 7 6 7 7 8 8 9 9 8 9 9 8 ]
May someone help me?

採用された回答

Andrei Bobrov
Andrei Bobrov 2019 年 10 月 3 日
編集済み: Andrei Bobrov 2019 年 10 月 3 日
C = [1 2 1 2 1 2 1 2 4 2 4 2 4 2 4 2 6 2 6 2 6 7 6 7 6 7 6 7 7 7 7 7 8 8 8 8 9 9 9 9 ];
CC = [C(:);max(C(:))+1];
j = 1;
for i = 2:numel(CC)
if numel(unique(CC(j:i))) > 2
P = CC(j:i-1);
CC(j:i-1) = P(randperm(i-j));
j = i;
end
end
R = CC(1:end-1);
  4 件のコメント
luca
luca 2019 年 10 月 7 日
Hi Andrei I have to ask you an important thing, in your code the number of diversity remain the same? I mean, if in the initial array C I have 2 repeated ten times, then also in R we will find 2 ten times?
please let me know
thanks
Andrei Bobrov
Andrei Bobrov 2019 年 10 月 8 日
Yes.

サインインしてコメントする。

その他の回答 (1 件)

John D'Errico
John D'Errico 2019 年 10 月 3 日
I fail to see the problem, although you are the only one who knows the rules that created this vector, so you will know what to search for.
You just use a while loop.
  1. Whatever the first element is, (here, it is a 1.) Locate the first element that is not a 1. That will be the number 2.
  2. Now, locate the first element that is not a 1 or 2. Then permute everything between elements 1 and the element that precedes the 4.
Iterate the above steps until the vector is fully permuted.
However, there will be no simply vectorized solution that will magically do what you want. It is just a question of writing the brute force code. As I said, a sequence of finds inside a while loop. Once you find the bounds on the current set of elements, then you do a permutation.
  1 件のコメント
luca
luca 2019 年 10 月 3 日
編集済み: luca 2019 年 10 月 3 日
Sorry John, probably I'm a begginer and for me it's difficult to understand what you mean. But if I'm able to find each subset then I will use the command
S = v(randperm(numel(v))); % where v is the generic subset
for each subset and fill a new vector F with each subset rearrange.
That was my idea, but I don't know how to implement it.
Probably the while loop is a better idea, but I have no idea of how to implement it

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by