我有以下代码来实现电梯:
public class Elevator{
Direction dir;
int floorNum;
int capacity;
public void moveUp{
dir = Direction.Up;
}
public void moveDown{
dir = Direction.Down
}
public boolean isMoving{
returns dir.equals(Direction.STATIONARY);
}
}
public class ElevatorController{
Elevator[] elevators;
PriorityQueue<Integer> queue = new PriorityQueue<Integer>;
public void buttonPressed{Direction d, int fromFloot, int toFloor){
}
}
我读到实现电梯的一个好方法是实现一个优先队列来获得电梯,但我不确定如何实现。
队列将包含目标楼层。
您建议如何实现它?
最佳答案
一种可能性是使用两个单独的 TreeSet 来对楼层进行排序,up
和 down
。如果您要在 currentFloor
上方添加一个楼层,则将其添加到 up
,如果您要在 currentFloor
下面添加一个楼层,则将其添加到 向下
;如果您要添加等于 currentFloor
的楼层,则将其丢弃。 TreeSet 自动丢弃重复项。在确定下一层访问时,如果direction == UP则访问up
下一个最低层,如果direction == DOWN则访问down
下一个最高层>.
或者,您可以使用单个 TreeSet 并尝试提出一个考虑电梯方向的聪明比较器,但这似乎比它的值(value)更麻烦。
private TreeSet<Integer> up = new TreeSet<>(); // floors above currentFloor
private TreeSet<Integer> down = new TreeSet<>(); // floors below currentFloor
private int currentFloor = 0;
private Enum direction = direction.UP;
public void addFloor(int f) {
if(f < currentFloor) {
down.add(f);
} else if(f > currentFloor) {
up.add(f);
}
// else f == currentFloor, so don't add the floor to either queue
}
public int nextFloor() {
if(direction == direction.DOWN) {
return down.pollLast(); // highest floor in down, or null if empty
} else {
return up.pollFirst(); // lowest floor in up, or null if empty
}
}
关于java - 在电梯中实现优先队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16304995/