In a sequence of 0 and 1, how to make sure that no same values appear more than 2 times consecutively?
3 ビュー (過去 30 日間)
古いコメントを表示
I am generating a sequence of equal number of 0's and 1's . A = [ 0 1 1 0 1 1 1 0 0 1 0 0] My goal is to not have either 0 or 1 be repeated more than 2 times consecutively. in the above array A, you can see that 1 1 1 appears so somehow I need to switch it around so that one of them becomes 0 and if there is something like 0 0 0 then switch one of them to 1. I have tried few algorithms which work for few iterations but then run into an error.
if true
nums = mod( reshape(randperm(1*12), 1, 12), 2)
%%%%%algorithm to check for a condition repeating more than 2 times and fix it
for i = 1:length(nums)-2
if nums(i+1)==nums(i) & nums(i+2) ==nums(i)
if nums(i) == 1
nums(i+2) = 0;
else
nums(i+2) = 1;
end
end
end end
Any help would be appreciated. Thanks
10 件のコメント
John BG
2016 年 4 月 21 日
To Image Analyst:
from the question 'My goal is to not have either 0 or 1 be repeated more than 2 times consecutively.'
yes, you can have 010 or 0110, but you cannot have 01110 ..
回答 (3 件)
Jon
2016 年 4 月 19 日
編集済み: Jon
2016 年 4 月 19 日
Just modify your loop a little bit:
for i = 3:length(nums)
if nums(i) == nums(i-1) && nums(i) == nums(i-2)
if nums(i) == 1
nums(i) = 0;
else
nums(i) = 1;
end
end
end
Oh, I see that you also require the same number of 1s and 0s. This doesn't ensure that. The easiest solution (though certainly not the fastest) is to add a check at the end that there are the same number; if not, reiterate until so.
John BG
2016 年 4 月 21 日
Dushyant
the following generates sequences of random even length with your requirements of no longer than paired 1s or paired 0s bursts:
L=randi([0 10],1,1) % choose random amount of ones
header=randi([0 1],1,2) % choose random intitial 2 bits
S=zeros(1,2*L) % init sequence to all zeros
S(1)=header(1);S(2)=header(2) % cast header
k=3 % pointer to sequence bit to decide
n1s=L;n0s=L % meters counting how many ones and zeros left in each clip
while (n1s>0 && n0s>0)
if (S(k-2)==0 && S(k-1)==0 && n1s>0) % previous bits are 00
S(k)=1
n1s=n1s-1
k=k+1
end
if (S(k-2)==1 && S(k-1)==1 && n0s>0) % previous bits are 11
S(k)=0
n0s=n0s-1
k=k+1
end
if (S(k-2)==0 && S(k-1)==1) % previous bits are 01
S(k)=randi([0 1],1,1)
if (S(k)==1 && n1s>0)
n1s=n1s-1
end
if (S(k)==0 && n0s>0)
n0s=n0s-1
end
k=k+1
end
if (S(k-2)==1 && S(k-1)==0) % previous bits are 10
S(k)=randi([0 1],1,1)
if (S(k)==1 && Ln1s>0)
n1s=n1s-1
end
if (S(k)==0 && n0s>0)
n0s=n0s-1
end
k=k+1
end
end
If you find this answer of any help solving your question, please click on the thumbs-up vote link, or mark it as accepted answer
thanks in advance
John
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Multidimensional Arrays についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!