Longest Run Tosses Matlab

2 次查看(过去 30 天)
KB
KB 2020-6-5
评论: Rena Berman 2020-10-12
Write an efficient function which computes the length of the longest run of heads in an arbitrary sequence of heads and tails ?
The excercise is about a coin toss and i would really appreciate if someone could help me with this excercise.
  6 个评论
madhan ravi
madhan ravi 2020-6-5
KBB it's really clear that your professor found this link ;) and thank you for disrespecting others effort.
Rena Berman
Rena Berman 2020-10-12
(Answers Dev) Restored edit

请先登录,再进行评论。

回答(3 个)

Walter Roberson
Walter Roberson 2020-6-5
at any one time you only need a few pieces of information:
  • are you currently in a run
  • length of the current run
  • maximum length of run encountered so far
if you are not in a run and you encounter a T then move on to the next entry
if you are in a run and you encounter a T then compare the length of the current run to the maximum so far to determine if you have a new record. Afterwards either way mark yourself as no longer being in a run. then move on to the next entry.
if you are in a run and encounter a H then increment the length of the current run. Then move on to the next entry.
I left out a detail that you should be able to catch.
You can get away with using just two variables aside from the loop index.

KSSV
KSSV 2020-6-5
编辑:KSSV 2020-6-5
N = 2 ; % [1- heads, 2-tails]
toss = 100 ; %number of tossings
state = zeros(toss,1) ;
for i = 1:toss
state(i) = randperm(N,1) ;
end
% split the states which are continuous 1 and/or 2
S = mat2cell(state, diff([0; find(diff(state)); size(state,1)]));
% Get the length of sequence of states
L = cellfun(@length,S) ;
% Get the maximum length sequence
[val,id] = max(L) ;
fprintf("State:%d is repeated maximum of %d times\n",unique(S{id}),val)
  2 个评论
Walter Roberson
Walter Roberson 2020-6-5
this was clearly a homework assignment :(
KSSV
KSSV 2020-6-5
You should understand first how/ what the code is.
Thanks is accepting the answer. :)

请先登录,再进行评论。


Stephen23
Stephen23 2020-6-5
编辑:Stephen23 2020-6-5
Simpler and more efficient:
>> N = 17; % number of tosses
>> V = randi(2,1,N) % 1=tails 2=heads
V =
2 1 2 2 2 2 2 2 1 1 2 2 1 1 1 2 2
>> D = diff([false,V==2,false]); % 2=heads
>> L = find(D<0)-find(D>0);
>> max(L)
ans = 6

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

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

Start Hunting!

Translated by