%% Lab 6: Finite Monkey Simulation - Wednesday, 2016-03-16
% This script is a finite simulation of the Infinite Monkey Theorem.

%% Define Constants
MPY = 525600;   %minutes per year
CPW = 5;        %characters per word
CPL = 72;       %characters per line

%% Define Simulation Parameters
phrase = ' code ';
numYears = 10;
wpm = 150;

%% Calculate Lines

%calculate total number of words
totalWords = MPY*wpm*numYears;

%calculate total number of characters
totalChar = totalWords*CPW;

%calculate total number of lines
totalLines = round(totalChar/CPL);
lpy = totalLines/numYears;

%% Simulate Finite Monkeys

%initialize counter
counter = 0;

%loop through lines
for i = 1:totalLines

    %print year
    if mod(i,lpy) == 0
        fprintf('- Year %d -\n', i/lpy);
    end
    
    %generate line of random characters
    line = randi([97 123], 1, CPL);

    %change 123 to 32 (i.e. changing character to blank space)
    line(line == 123) = 32;

    %convert line of digits to string
    line = char(line);

    %search for phrase in line
    idx = strfind(line, phrase);
    instances = length(idx);

    %print message if phrase is found
    if instances > 0
        line = strrep(line, phrase, upper(phrase));

        %display message
        if instances > 1
            fprintf('Found %d instances in line %d:\n%s\n', instances, i, line);
        else
            fprintf('Found 1 instance in line %d:\n%s\n', i, line);
        end %display

        %increase counter by number of instances
        counter = counter + instances;

    end %instance
end %lines
    
%display summary message
fprintf('A total of %d instances were found\n', counter);