Invitation to Computer Science 8th Edition

Published by Cengage Learning
ISBN 10: 1337561916
ISBN 13: 978-1-33756-191-4

Chapter 2 - Exercises - Page 88: 18b

Answer

b) Replace "Increment $k$ by 1 " with the loop: While $\left(\left(T_{k} \text { is not a blank space) or }\left(T_{k+m+1} \text { is not a blank space) }\right) \text { and }\right.\right.$ $(k \leq n-m)$ do $\quad$ Increment $k$ by 1 End loop

Work Step by Step

The task is to have the algorithm only find the complete word "and." We could modify the algorithm in such a way that it will not even check the words which are longer than the pattern we are looking for which are words longer than $m$ characters. We could modify the line which increments $k$ by 1 to shift the starting location for the next attempted match. Replace "Increment $k$ by 1 " with the loop: While $\left(\left(T_{k} \text { is not a blank space) or }\left(T_{k+m+1} \text { is not a blank space }\right) \text { ) and }\right.\right.$ $(k \leq n-m)$ do $\quad$ Increment $k$ by 1 End loop This way, it checks whether the actual position and the position $\mathrm{m}+1$ places after it, are both blank spaces. When that is true, we know that there is a $m$ -characters long word between the blanks, which is exactly what we need. The third condition $(k \leq n-m)$ must also be included. It will stop shifting positions when there is just enough space left to fit one $m$ -characters word.
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.