% script longLifeBulb
% Simulates the random change on a digit board and see which one 
% 1. is on for the longest time
% or
% 2. switches most frequently

M = 100000; % repeat M times of random change
nRow = 7;   % size of the digit board
nCol = 5;

digits = TheDigits;

% generates the initial digit
n = ceil(rand*10);

nLast = digits{n};            % "on" time of each bulb
nSwitch = zeros(nRow, nCol);  % number of switches of each bulb

for k = 1:M
    % the next digit
    nextn = ceil(rand*10);
    % update the switch time and lasting time
    nSwitch = nSwitch + abs(digits{nextn} - digits{n});
    nLast = nLast + digits{nextn};
    n = nextn;
end

% find the bulb that was on the longest
longVector= mat2vec(nLast);
[maxelem,maxindex]= max(longVector);
[row,col]= i2rc(maxindex,nRow,nCol);
fprintf('The bulb that was on for the longest time: (%d,%d)\n',...
        row,col);

% find the bulb that was switched most often
switchVector= mat2vec(nSwitch);
[maxelem,maxindex]= max(switchVector);
[row,col]= i2rc(maxindex,nRow,nCol);
fprintf('The bulb that was switched most often: (%d,%d)\n',...
        row,col);
