8.6 code consistency issue

#1

The solution for 8.6 (sunset view) operates at the tail of the Deque rather than the head, which although functionally works, could still confuse readers. It would be better to consistently use peekFirst instead of getLast, removeFirst instead of removeLast, and addFirst instead of addLast. 8.5 also has the same problem on the book but I see the code in github is already fixed.

Thanks!

0 Likes

#2

Hi @ray,

Thanks for your suggestion. Would you mind to share with us your suggestion as I think in this problem, we do need to use getLast and removeLast for this problem.

It would be great if you can share the code here.

0 Likes

#3
  public static Deque<BuildingWithHeight> examineBuildingsWithSunset(
      Iterator<Integer> sequence) {
    int buildingIdx = 0;
    Deque<BuildingWithHeight> buildingsWithSunset = new LinkedList<>();
    while (sequence.hasNext()) {
      Integer buildingHeight = sequence.next();
      while (!buildingsWithSunset.isEmpty()
             && (Integer.compare(buildingHeight,
                                 buildingsWithSunset.**peekFirst**().height)
                 >= 0)) {
        buildingsWithSunset.**removeFirst**();
      }
      buildingsWithSunset.**addFirst**(
          new BuildingWithHeight(buildingIdx++, buildingHeight));
    }
    return buildingsWithSunset;
  }

The difference from the book’s solution is that the elements in the returned dequeue is in reversed order, which i think is ok. I just wanted the methods to be strictly consistent with the stack operations, i.e., it returns exactly same result as when we use the peek(), push() and pop() methods.

0 Likes

#4

Hi @ray,

I think the difference here is that it returns the id instead of the whole object and it makes no difference if we need to extract the id of it. So I think I will still keep Last here.

0 Likes