Other 2012 FR Questions FR other years Be Prepared Home
A-3
Part (a)
  public int findHorseSpace(String name)
  {
    for (int i = 0; i < spaces.length; i++)
      if (spaces[i] != null && spaces[i].getName().equals(name)) 1
        return i;
    return -1;
  }
Notes:
  1. Check for null first to avoid NullPointerException.


Part (b)
  public void consolidate()
  {
    Horse[] temp = new Horse[spaces.length]; 1
    int j = 0;
    for (int i = 0; i < spaces.length; i++)
    {
      if (spaces[i] != null)
      {
        temp[j] = spaces[i];
        j++;
      }
    }
    spaces = temp;
  } 2
Notes:
  1. The values are initialized to null by default.
  2. This safe and expedient but inelegant solution that uses a temporary array is acceptable in the context of the exam.  An alternative solution:
      public void consolidate()
      {
        // 1. Find the first empty space:
        int emptySpaceIndex = 0;
        while (emptySpaceIndex < spaces.length && spaces[emptySpaceIndex] != null)
          emptySpaceIndex++;
    
        // 2. Move horses:
        int i = emptySpaceIndex + 1;
        while (i < spaces.length)
        {
          if (spaces[i] != null)
          {
            spaces[emptySpaceIndex] = spaces[i];
            spaces[i] = null;
            emptySpaceIndex++;
          }
          i++;
        }
      }
    Another alternative, in which we look for the first empty space for each horse — not very efficient:
      public void consolidate()
      {
        int emptySpaceIndex = 0;
        for (int i = 0; i < spaces.length; i++)
        {
          if (spaces[i] != null)
          {
            // Find the first empty space, if any, preceeding i:
            while (emptySpaceIndex < i && spaces[emptySpaceIndex] != null)
              emptySpaceIndex++;
            if (i != emptySpaceIndex)
            {
              spaces[emptySpaceIndex] = spaces[i];
              spaces[i] = null;
            }
          }
        }
      }

Other 2012 FR Questions | Back to Contents

Copyright © 2012 by Skylight Publishing
support@skylit.com