elevator design example

来源:互联网 发布:linux给用户赋root权限 编辑:程序博客网 时间:2024/06/03 12:33

转自:http://careercup.com/question?id=5698327039442944


repose with format corrected*public class Elevator {public static final int MAX_FLOORS = 50;// upward floor queueprivate PriorityQueue<Integer> floors_up = new PriorityQueue<Integer>(MAX_FLOORS);// downward floor queueprivate PriorityQueue<Integer> floors_down = new PriorityQueue<Integer>(MAX_FLOORS, new Comparator<Integer>(){public int compare(Integer arg0, Integer arg1) {return arg1.compareTo(arg0);}});// effective floor queueprivate PriorityQueue<Integer> floors = floors_up;// current floorprivate int current = 0;public void userCallAt(int where) {setTarget(where);}public void setTarget(int target) {// ignore if target is currentif (target == current) {return;}// add target to right queueif (floors == floors_up) {if (target < current) {floors_down.offer(target);} else {floors_up.offer(target);}} else {if (target > current) {floors_up.offer(target);} else {floors_down.offer(target);}}// swap queue to turn around the elevatorif (floors.isEmpty()) {floors = (floors == floors_up ? floors_down : floors_up);}}public int getTarget() {if (!floors.isEmpty()) {return floors.peek();}if (floors_up.isEmpty() && floors_down.isEmpty()) {return current;}floors = (floors == floors_up ? floors_down : floors_up);return floors.peek();}public int getCurrent() {return current;}public void step(int target) {if (target > current) {current++;} else {current--;}}public void stop() {floors.poll();}public void move() {while (getCurrent() != getTarget()) {do {step(getTarget());} while (getCurrent() != getTarget());stop();}}}

0 0
原创粉丝点击