%
% Homework 5
% letterFreqs.m
% CS 1109, Summer 2011
% July 25
%
% letterFreqs: Generates a frequency count of the letters in input string
%
%   This function accepts an input string and computes the frequency of
%   occurence of each letter of the alphabet in the string. The letters are
%   treated in a case-insensitive manner. Punctuation marks, numbers and
%   other symbols are ignored. The output is a vector containing the
%   frequency data. The first element of the vector contains the number of
%   appearances of the letter `a' (or `A'), the second element counts the
%   appearances of `b' and so on.
%
% USAGE: freqs = letterFreqs(str);
%
function histData = letterFreqs(cipherTextString)

% Set counts to zero
histData = zeros(1, 26);

% Step through the input string one character at a time
for i = 1 : length(cipherTextString)
    % If the current character is a lower-case letter, then increase the
    % count in the appropriate vector entry
    if (cipherTextString(i) >= 'a' && cipherTextString(i) <= 'z')
        index = cipherTextString(i) - 'a' + 1; % this maps 97->1, 98->2 etc
        histData(index) = histData(index) + 1;
    % Similarly, handle the upper-case letters
    elseif (cipherTextString(i) >= 'A' && cipherTextString(i) <= 'Z')
        index = cipherTextString(i) - 'A' + 1; % this maps 65->1, 66->2 etc
        histData(index) = histData(index) + 1;
    end
    % We have no else-block --- this is an elegant way to ignore all other
    % symbols
end

end

%
% Common mistakes / other observations:
%
% 1) One approach adopted by some was to step through the letters of the
% alphabet one at a time, and count the number of appearances of each
% letter in the given string. Note that this is a rather inefficient
% solution -- in particular, this nested loop approach has an outer loop
% that iterates over all the letters of the alphabet (and hence runs 26
% times) and an inner loop that iterates over all the characters in the
% string (and thus runs n = length(cipherTextString) times). In total, this
% solution requires 26*n iterations of the loop body. In contrast, the
% solution above only performs a single pass through the input string and
% thus only performs n iterations of the loop body -- a speed-up factor of 
% 26!
%


