Professional Documents
Culture Documents
AdvancedAlgorithms Assignment
AdvancedAlgorithms Assignment
task/problem. One of the algorithms will be recursive, and the other non-recursive.
The algorithm should adhere to the characteristics of algorithms including being nonambiguous,
and finite among others.
Problem:
Word Frequency Counter
Objective:
This program analyzes the text in a document and keeps track of how many times a particular
word appears within it.
Recursive Algorithm
function word_frequency_counter_recursive(document, target_word):
if document is empty:
return 0
else:
words = split document into words
if first word in words is equal to target_word:
return 1 + word_frequency_counter_recursive(rest of words, target_word)
else:
return word_frequency_counter_recursive(rest of words, target_word)
Characteristics
● Has recursive calls
● Has a base case(if document is empty)
● Utlizes subproblem decomposition
Explained Algorithm
Building Blocks:
NonRecursive Algorithm
function word_frequency_counter_non_recursive(document, target_word):
words = split document into words
word_count = 0
for each word in words:
if word is equal to target_word:
increment word_count
return word_count
Explained Algorithm:
Building Blocks:
Input Parameters: The algorithm takes two input parameters:
● document: The document containing the word we want to count.
● target_word: The specific word intended for counting within the document.
Base Case: The algorithm starts with a base case to terminate the recursion:
● if document is empty:: If the document is empty, it returns 0, signifying that there
are no occurrences of the target word in the remaining text.
if document is empty:
return 0
Main Logic (Non-Recursive): When the document is not empty, the algorithm proceeds
with the main logic in a non-recursive manner:
● words = split document into words: The document is split into individual words,
creating a list of words.
words = split document into words
● word_count = 0: Initialize a variable word_count to 0. This variable will be used to
keep track of the number of occurrences of the target word.
word_count = 0
● for each word in words:: The algorithm iterates through each word in the list of
words.
for each word in words:
● if word is equal to target_word:: For each word, it checks if the word is equal to
the target_word.
if word is equal to target_word:
● increment word_count: If the condition is met (the word is equal to the
target_word), it increments the word_count by 1, indicating that an occurrence of
the target word is found.
increment word_count
Return Result: After processing all the words in the document, the algorithm returns the
final word_count, which represents the total number of occurrences of the target_word in
the document.
return word_count
This non-recursive algorithm relies on iteration and a counter toscan the document sequentially,
word by word, and to keep track of occurrences.
Characteristics