HorseBarn free response answer 2

The HorseBarn problem from the 2012 AP Computer Science Exam is typical of free response problems that test arrays.

Review the HorseBarn free response solution with AP CS Tutor Brandon Horn.

HorseBarn Part (a): findHorseSpace

  public int findHorseSpace(String name)
  {
    for(int i = 0; i < spaces.length; i++)
    {
      Horse h = spaces[i];
      if(h != null && name.equals(h.getName()))
          return i;
    }
    
    return -1;
  }

HorseBarn Part (b): consolidate

  public void consolidate()
  {
    int nextSpace = 0;

    for(int i = 0; i < spaces.length; i++)
    {
      if(spaces[i] != null)
      {
        spaces[nextSpace] = spaces[i];
        nextSpace++;
      }
    }

    for(int i = nextSpace; i < spaces.length; i++)
      spaces[i] = null;
  }

HorseBarn Part (b): consolidate – alternate solution 1

  public void consolidate()
  {
    Horse[] newSpaces = new Horse[spaces.length];
    int newIndex = 0;
    
    for(int oldIndex = 0; oldIndex < spaces.length; oldIndex++)
    {
      if(spaces[oldIndex] != null)
      {
        newSpaces[newIndex] = spaces[oldIndex];
        newIndex++;
      }
    }
    
    spaces = newSpaces;
  }

HorseBarn Part (b): consolidate – alternate solution 2

public void consolidate()
{
  for(int i = 0; i < spaces.length; i++)
  {
    if(spaces[i] == null)
    {
      int nextHorse = i + 1;
      while(nextHorse < spaces.length && spaces[nextHorse] == null)
        nextHorse++;

      if(nextHorse < spaces.length)
      {
        spaces[i] = spaces[nextHorse];
        spaces[nextHorse] = null;
      }
    }
  }
}

Get AP CS Help

2012 AP CS Exam Free Response Solutions

2 thoughts on “HorseBarn free response answer

  1. Reply Orangey Feb 15,2016 2:08 am

    Could you tell me what’s wrong with this code? :

    public void consolidate() {
      int counter = 0;
      for (int i=0; i<spaces.length; i++) {
        Horse space = space[i];
        if (space != null) {
          spaces[counter] = space;
          if (counter != i) {
            space = null;
          }
          counter++;
        }
      }
    }

    • Reply Brandon Horn Feb 17,2016 12:41 pm

      The line:
      space = null;

      should read:
      spaces[i] = null;

      Setting the value of space to null does not change the value inside the array.

      The code is also missing an s on the line:
      Horse space = space[i];

Leave a Reply