Other 2017 FR Questions FR other years Be Prepared Home
A-3
Part (a)
  public void replaceNthOccurrence(String str, int n, String repl)
  {
    int i = findNthOccurrence(str, n);
    if (i >= 0)
      currentPhrase = currentPhrase.substring(0, i) + repl +
                             currentPhrase.substring(i + str.length());
  }


Part (b)
  public int findLastOccurrence(String str)
  {
    int i = -1, i2 = 0;
    int n = 1;

    while (i2 >= 0)
    {
      i2 = findNthOccurrence(str, n);
      if (i2 >= 0)
        i = i2;
      n++;
    }
    return i;
  } 1, 2
Notes:
  1. The question description says (top of Page 15): "You must use findNthOccurrence appropriately to receive full credit." So just
        return currentPhrase.lastIndexOf(str);
    won't receive full credit.  This is why it is important to always read carefully the entire question.  It is also important to quickly make the safest guess of the real intent of the question, rather than exploiting possible ambiguities.  For example, what does "appropriately" really mean here? Will the following solution receive full credit?
      public int findLastOccurrence(String str)
      {
        for (int i = currentPhrase.length() - str.length(); i >= 0; i--)
          if ((new Phrase(currentPhrase.substring(i))).findNthOccurrence(str, 1) == 0)
            return i;
        return -1;
      }
    We believe it will, but we will know for sure after the exams have been graded.

  2. Alternative solutions, starting at high n and going down:
      public int findLastOccurrence(String str)
      {
        for (int n = currentPhrase.length(); n > 0; n--)
        {
          int i = findNthOccurrence(str, n);
          if (i >= 0)
            return i;
        }
        return -1;
      }
    Or:
      public int findLastOccurrence(String str)
      {
        int n = currentPhrase.length(), i = -1;
        while (n > 0 && i == -1)
        {
          i = findNthOccurrence(str, n);
          n--;
        }
        return i;
      }

Other 2017 FR Questions | Back to Contents

Copyright © 2017 by Skylight Publishing
support@skylit.com