Consider a software system that models a horse barn. Classes that represent horses implement the following interface.

public interface Horse
{
   /** @return the horse's name */
   String getName();

   /** @return the horse's weight */
   int getWeight();
}

A horse barn consists of N numbered spaces. Each space can hold at most one horse. The spaces are indexed starting from 0; the index of the last space is N – 1. No two horses in the barn have the same name. The declaration of the HorseBarn class is shown below.

Write the HorseBarn method consolidate. This method consolidates the barn by moving horses so that the horses are in adjacent spaces, starting at index 0, with no empty spaces between any two horses. After the barn is consolidated, the horses are in the same order as they were before the consolidation.

public class HorseBarn
{
   /** The spaces in the barn. Each array element holds a reference to the horse
    * that is currently occupying the space. A null value indicates an empty
    * space.
    */
   private Horse[] spaces;

   /** Consolidates the barn by moving horses so that the horses are in
    *  adjacent spaces, starting at index 0, with no empty space between
    *  any two horses.
    * Postcondition: The order of the horses is the same as before the
    *  consolidation.
    */
   public void consolidate()
   { /* to be implemented in part (b) */ }
}

如何解题

这道题的解法之一是创建一个与spaces同样大小的临时数组,然后循环遍历当前的spaces数组,将非null元素复制到临时数组中。



0:00

Which loop should you use to loop through all the digits of the number?

当明确循环次数的时候,使用for
1

当进行循环时,我们需要检查非null位置。

How do we check if the space at the current index isn’t null?

作为数组,spaces需要用[]来存取其元素,而==!=可以用于做null相关的判断。
3

以下是本题的参考答案。

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

陈 欣

AADPS创始人

发表评论