Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package elevator;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Random;
- public class Elevator
- {
- private static final int CAPACITY = 3;
- private static final int PERSONS_AT_START = 5;
- private static final int TOTAL_FLOORS = 5;
- private int direction;
- private int currentFloor = 1;
- private final List<Person> waitingPersons = new ArrayList<Person>();
- private final List<Person> personsIn = new ArrayList<Person>();
- private final Random random = new Random();
- public static void main(String[] args) {
- new Elevator().run();
- }
- public void run() {
- for (int i = 1; i <= PERSONS_AT_START; i++) {
- final Person person = new Person(this, i);
- waitingPersons.add(person);
- }
- while (!waitingPersons.isEmpty() || !personsIn.isEmpty()) {
- unloadPeople();
- loadPeople();
- moveToNextFloor();
- }
- }
- private void moveToNextFloor() {
- if (currentFloor == 1) {
- direction = 1;
- } else if (currentFloor == TOTAL_FLOORS) {
- direction = -1;
- }
- currentFloor += direction;
- System.out.format("Moving to floor %d%n", currentFloor);
- }
- private boolean hasCapacity() {
- return personsIn.size() < CAPACITY;
- }
- private void loadPeople() {
- if (hasCapacity()) {
- for (final Iterator<Person> iter = waitingPersons.iterator();
- iter.hasNext();)
- {
- final Person person = iter.next();
- if (person.getStartFloor() == currentFloor) {
- iter.remove();
- personsIn.add(person);
- System.out.format("Person %d entered at floor %d%n",
- person.getId(), currentFloor);
- }
- if (!hasCapacity()) {
- return;
- }
- }
- }
- }
- private void unloadPeople() {
- for (final Iterator<Person> iter = personsIn.iterator();
- iter.hasNext();)
- {
- final Person person = iter.next();
- if (person.getEndFloor() == currentFloor) {
- // person.delivered();
- iter.remove();
- System.out.format("Person %d exited at floor %d%n",
- person.getId(), currentFloor);
- }
- }
- }
- public int getRandomFloor() {
- return random.nextInt(TOTAL_FLOORS) + 1;
- }
- }
- package elevator;
- public class Person
- {
- private final int id;
- private final int startFloor;
- private int endFloor;
- public Person(Elevator elevator, int id) {
- this.id = id;
- startFloor = elevator.getRandomFloor();
- while ((endFloor = elevator.getRandomFloor()) == startFloor) {
- // try again
- }
- System.out.format("Person %d want to ride from %d to %d%n",
- id, startFloor, endFloor);
- }
- public int getId() {
- return id;
- }
- public int getStartFloor() {
- return startFloor;
- }
- public int getEndFloor() {
- return endFloor;
- }
- // public void delivered() {
- // }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement