Question

This is a repost of my question from before. I am having trouble writting the code...

This is a repost of my question from before. I am having trouble writting the code for this project. Below is the project description with various methods and classes the code in C++ should implement.

Project Description

The goal of this project is to design and develop C++ code and algorithms to control a bank of elevators, which services many floors and transports people “efficiently ", that is, as per the given specifications. A second goal is to effectively employ object oriented design, through appropriate use of classes, data structures and Standard Template Libraries (STLs).

Problem Specifications

‌• The elevator bank has m elevators and services n floors. As an example, you may choose m = 3 and n = 10.

‌• Each elevator can stop at every floor.

‌• The direction of an elevator has three states up, down and standing. Each elevator can carry up to a max of N max persons.

‌• The program loops through discrete time steps t = 1; 2…T stop, where T stop is an input parameter.

‌• At each time step, either 0, 1 or 2 persons arrive at a floor. This information can be read from an input data file, as described in 1.3.

‌•An elevator takes k time step to move up or down by k floors, if it doesn't stop. For example, to move from floor 4 to floor 5 requires one time step. And to move from floor 7 to floor 3 requires 4 time steps.

‌• When an elevator stops at a floor, for either passenger pick up or drop off, it does so for one time step.

‌•When a person arrives on a floor, they are assigned the “nearest "elevator. Here nearest is defined in the number of time steps. For example, let us say a person arrives on floor 5, and wants to go up. Elevator E1 on floor 2, moving in the up direction, with no stops, is 3 time steps away. Elevator E2 on floor 6, moving in the down direction and headed for floor 3 is 6 time steps away. Therefore, the person is assigned elevator E1.

‌• Each arriving person has an arrival floor, destination floor and the assigned elevator as its data members.

‌• When a person is assigned an elevator, their arrival floor and destination floor go in the queue or the list of the elevator stops.

‌• Each elevator contains a list of stops, which gets updated at each time step.

‌• An elevator moving up (down) continues to move up (down), until it exhausts all the stops in its list.

Class Design and STLs

You must make appropriate use of classes and class objects, class data members, class methods, constructors/destructors to implement your code.

Here are some suggested classes and their data members:

‌• Person class with ID, arrival floor, destination floor and assigned elevator. An example ID for a person maybe P1A3D5, for person 1, arrival floor 3 and destination floor 5. This will make it easier to generate and track test input and output.

‌• Elevator class with direction, number of people and list of stops.

Think of the STL containers you will be utilizing. For example, a list allows for easy insertion and removal of elements, a vector can change size, and you can push and pop elements at the end of it, a deque allows for fast insertion and deletion of elements at both ends.

Input Data

‌•The input data consists of the arrivals on each floor, at time steps t = 1. 2… T Stop. At each time step, the program reads in each arriving person, for each floor, and processes this data. For example, for n = 10 floors, and at time step t = 1, the arrivals maybe P1A1D4 and P2A1D5 on floor 1, P1A3D1 and Pf2A3D7 on floor 3, and 0 on the remaining floors.

Program Output

Generate appropriate output for a given input test data, which displays the information, that is, people getting on and off each floor, for each time step, for say 10 consecutive time steps.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

A very common example to show the details of implementing a user-defined class is to construct a class to implement the abstract data type Fraction. We have already seen that Python provides a number of numeric classes for our use. There are times, however, that it would be most appropriate to be able to create data objects that “look like” fractions.

A fraction such as 3535 consists of two parts. The top value, known as the numerator, can be any integer. The bottom value, called the denominator, can be any integer greater than 0 (negative fractions have a negative numerator). Although it is possible to create a floating point approximation for any fraction, in this case we would like to represent the fraction as an exact value.

The operations for the Fraction type will allow a Fraction data object to behave like any other numeric value. We need to be able to add, subtract, multiply, and divide fractions. We also want to be able to show fractions using the standard “slash” form, for example 3/5. In addition, all fraction methods should return results in their lowest terms so that no matter what computation is performed, we always end up with the most common form.

In Python, we define a new class by providing a name and a set of method definitions that are syntactically similar to function definitions. For this example,

class Fraction:

   #the methods go here

provides the framework for us to define the methods. The first method that all classes should provide is the constructor. The constructor defines the way in which data objects are created. To create a Fractionobject, we will need to provide two pieces of data, the numerator and the denominator. In Python, the constructor method is always called __init__ (two underscores before and after init) and is shown in Listing 2.

Listing 2

class Fraction:

    def __init__(self,top,bottom):

        self.num = top
        self.den = bottom

Notice that the formal parameter list contains three items (self, top, bottom). self is a special parameter that will always be used as a reference back to the object itself. It must always be the first formal parameter; however, it will never be given an actual parameter value upon invocation. As described earlier, fractions require two pieces of state data, the numerator and the denominator. The notation self.num in the constructor defines the fraction object to have an internal data object called num as part of its state. Likewise, self.den creates the denominator. The values of the two formal parameters are initially assigned to the state, allowing the new fraction object to know its starting value.

To create an instance of the Fraction class, we must invoke the constructor. This happens by using the name of the class and passing actual values for the necessary state (note that we never directlyinvoke __init__). For example,

myfraction = Fraction(3,5)

creates an object called myfraction representing the fraction 3535 (three-fifths). Figure 5 shows this object as it is now implemented.

../_images/fraction1.png

The next thing we need to do is implement the behavior that the abstract data type requires. To begin, consider what happens when we try to print a Fraction object.

>>> myf = Fraction(3,5)
>>> print(myf)
<__main__.Fraction instance at 0x409b1acc>

The fraction object, myf, does not know how to respond to this request to print. The print function requires that the object convert itself into a string so that the string can be written to the output. The only choice myf has is to show the actual reference that is stored in the variable (the address itself). This is not what we want.

There are two ways we can solve this problem. One is to define a method called show that will allow the Fraction object to print itself as a string. We can implement this method as shown in Listing 3. If we create a Fraction object as before, we can ask it to show itself, in other words, print itself in the proper format. Unfortunately, this does not work in general. In order to make printing work properly, we need to tell the Fraction class how to convert itself into a string. This is what the print function needs in order to do its job.

Listing 3

def show(self):
     print(self.num,"/",self.den)
>>> myf = Fraction(3,5)
>>> myf.show()
3 / 5
>>> print(myf)
<__main__.Fraction instance at 0x40bce9ac>
>>>

In Python, all classes have a set of standard methods that are provided but may not work properly. One of these, __str__, is the method to convert an object into a string. The default implementation for this method is to return the instance address string as we have already seen. What we need to do is provide a “better” implementation for this method. We will say that this implementation overrides the previous one, or that it redefines the method’s behavior.

To do this, we simply define a method with the name __str__ and give it a new implementation as shown in Listing 4. This definition does not need any other information except the special parameterself. In turn, the method will build a string representation by converting each piece of internal state data to a string and then placing a / character in between the strings using string concatenation. The resulting string will be returned any time a Fraction object is asked to convert itself to a string. Notice the various ways that this function is used.

Listing 4

def __str__(self):
    return str(self.num)+"/"+str(self.den)
>>> myf = Fraction(3,5)
>>> print(myf)
3/5
>>> print("I ate", myf, "of the pizza")
I ate 3/5 of the pizza
>>> myf.__str__()
'3/5'
>>> str(myf)
'3/5'
>>>

We can override many other methods for our new Fraction class. Some of the most important of these are the basic arithmetic operations. We would like to be able to create two Fraction objects and then add them together using the standard “+” notation. At this point, if we try to add two fractions, we get the following:

>>> f1 = Fraction(1,4)
>>> f2 = Fraction(1,2)
>>> f1+f2

Traceback (most recent call last):
  File "<pyshell#173>", line 1, in -toplevel-
    f1+f2
TypeError: unsupported operand type(s) for +:
          'instance' and 'instance'
>>>

If you look closely at the error, you see that the problem is that the “+” operator does not understand the Fraction operands.

We can fix this by providing the Fraction class with a method that overrides the addition method. In Python, this method is called __add__ and it requires two parameters. The first, self, is always needed, and the second represents the other operand in the expression. For example,

f1.__add__(f2)

would ask the Fraction object f1 to add the Fraction object f2 to itself. This can be written in the standard notation, f1+f2.

Two fractions must have the same denominator to be added. The easiest way to make sure they have the same denominator is to simply use the product of the two denominators as a common denominator so that ab+cd=adbd+cbbd=ad+cbbdab+cd=adbd+cbbd=ad+cbbd The implementation is shown in Listing 5. The addition function returns a new Fraction object with the numerator and denominator of the sum. We can use this method by writing a standard arithmetic expression involving fractions, assigning the result of the addition, and then printing our result.

Add a comment
Know the answer?
Add Answer to:
This is a repost of my question from before. I am having trouble writting the code...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Solve it for java Question Remember: You will need to read this assignment many times to...

    Solve it for java Question Remember: You will need to read this assignment many times to understand all the details of the you need to write. program Goal: The purp0se of this assignment is to write a Java program that models an elevator, where the elevator itself is a stack of people on the elevator and people wait in queues on each floor to get on the elevator. Scenario: A hospital in a block of old buildings has a nearly-antique...

  • Write a C++ computer program that simulates the action of an elevator that is out of...

    Write a C++ computer program that simulates the action of an elevator that is out of order. After simulating the motion of the elevator, your program will display a bar chart that shows the number of times the elevator stays on each floor of a twenty-five-story building. When you arrive on the scene to begin studying the elevator, it is on the twelfth floor of the twenty-five-story building. Every five minutes the elevator either moves up one floor or down...

  • I NEED THE CODE FOR PART 2-MATH MODELING CLASS USING MATH LAB in thrve posed elevator...

    I NEED THE CODE FOR PART 2-MATH MODELING CLASS USING MATH LAB in thrve posed elevator problem, your assistant notified you that there are 60 workers operating on each of 5 floors atop the ground floor in your office building - 300 in total. The elevator occupancy is 10 people, and there are 3 elevators in total. In the worst-case scenario in terms of total transition time, on each elevator ride at least one person is getting off at each...

  • I am having trouble understanding how this code is able to use the contents of the...

    I am having trouble understanding how this code is able to use the contents of the header file. Can someone please provide comments in the main code to describe what is happening? (especially on the bool isNumber) THE MAIN CODE: #include<bits/stdc++.h> #include "MyCartesianPoint.h" #include <math.h> #include <iostream> using namespace std; bool isNumber(string s) {    if(!isdigit (s[0]))    {        if(s[0] != '-')        return false;               else if(s.length() == 1)        return false;...

  • I am having trouble understanding how this code is able to use the contents of the...

    I am having trouble understanding how this code is able to use the contents of the header file. Can someone please provide brief comments in the top code to show what is happening? THE CODE: #include<bits/stdc++.h> #include "MyCartesianPoint.h" #include <math.h> #include <iostream> using namespace std; bool isNumber(string s) {    if(!isdigit (s[0]))    {        if(s[0] != '-')        return false;               else if(s.length() == 1)        return false;    }       for...

  • Hello, I am having trouble with a problem in my C language class. I am trying...

    Hello, I am having trouble with a problem in my C language class. I am trying to make a program with the following requirements: 1. Use #define to define MAX_SIZE1 as 20, and MAX_SIZE2 as 10 2. Use typedef to define the following struct type: struct {     char name[MAX_SIZE1];     int scores[MAX_SIZE2]; } 3. The program accepts from the command line an integer n (<= 30) as the number of students in the class. You may assume that the...

  • Program must be written in C++: The goal for this Programming Project is to create a...

    Program must be written in C++: The goal for this Programming Project is to create a simple two-dimensional predator-prey simulation. In this simulation the prey are ants and the predator are doodlebugs. These critters live in a world composed of 20 x 20 grid of cells. Only one critter may occupy a cell at a time. The grid is enclosed, so a critter is not allowed to move off the edges of the world. Time is simulated in time steps....

  • Lab 5.1 C++ Utilizing the code from Lab 4.2, replace your Cargo class with a new...

    Lab 5.1 C++ Utilizing the code from Lab 4.2, replace your Cargo class with a new base class. This will be the base for two classes created through inheritance. The Cargo class will need to have virtual functions in order to have them redefined in the child classes. You will be able to use many parts of the new Cargo class in the child classes since they will have the same arguments/parameters and the same functionality. Child class one will...

  • /*hello everyone. my question is mostly related to the garagetest part of this assignment that i've...

    /*hello everyone. my question is mostly related to the garagetest part of this assignment that i've been working on. i am not sure how to read the file's contents AND put them into variables/an array. should it be in an arraylist? or maybe a regular array? or no arrays at all? i am also not sure how to call the factory method from garagec. i'm thinking something along the lines of [Garage garage = new GarageC.getInstance("GarageC", numFloors, areaofEachFloor);] but i...

  • Java - Car Dealership Hey, so i am having a little trouble with my code, so...

    Java - Car Dealership Hey, so i am having a little trouble with my code, so in my dealer class each of the setName for the salesman have errors and im not sure why. Any and all help is greatly appreciated. package app5; import java.util.Scanner; class Salesman { private int ID; private String name; private double commRate; private double totalComm; private int numberOfSales; } class Car { static int count = 0; public String year; public String model; public String...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT