Other 2016 FR Questions FR other years Be Prepared Home
A-2
Part (a)
  public LogMessage(String message)
  {
    int i = message.indexOf(":");
    machineId = message.substring(0, i);
    description = message.substring(i+1);
  }
Part (b)
  public boolean containsWord(String keyword)
  {
    return (" " + description + " ").indexOf(" " + keyword + " ") >= 0;
  } 1
Notes:
  1. It is much easier to pad description with spaces at each end than to consider special cases when keyword is at the beginning or at the end of description. The brute-force alternative is time-consuming and prone to errors:
      public boolean containsWord(String keyword)
      {
        int len = keyword.length();
        String d = description;
        while (true)
        {
          int i = d.indexOf(keyword);
          if (i < 0)
             return false;
          if ((i == 0 || d.substring(i-1, i).equals(" ")) &&
              (i == d.length() - len || d.substring(i + len, i + len + 1).equals(" ")))
                return true;
    
          /* Or, outside of the AP subset: 
          if ((i == 0 || d.charAt(i-1) == ' ') &&
              (i == d.length() - len || d.charAt(i + len) == ' '))
                return true; */
    
          d = d.substring(i + len);
        }
      }
Part (c)
  public List<LogMessage> removeMessages(String keyword)
  {
    List<LogMessage> removed = new ArrayList<LogMessage>();
    int i = 0;
    while(i < messageList.size())
    {
      LogMessage msg = messageList.get(i);
      if (msg.containsWord(keyword))
      {
        removed.add(msg);
        messageList.remove(i);
      }
      else
        i++;
    }
    return removed;
  } 1
Notes:
  1. You might be tempted to traverse messageList in reverse, but then you need to insert removed elements at the beginning of the removed list, which is inefficient.

Other 2016 FR Questions | Back to Contents

Copyright © 2016 by Skylight Publishing
support@skylit.com