Saturday, January 20, 2018

Programming Challenge 15.3 - TeamLeader Class

Example Files: TeamLeaderClass.7z

Note: A change to the Employee and ProductionWorker class has been made. Both classes now contain a print function.

Employee.h


#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_

#include <string>
using std::string;

#include <iostream>
using std::ostream;

class Employee
{
    private:
        string empName;                // Employee name
        int     empID;                      // Employee ID-number
        string empHireDate;           // Employee hire date

    public:   
        // Default constructor
        Employee()
        {
            empName = " ";
            empID = 0;
            empHireDate = " ";
        }

        // Parameterized constructor
        Employee(string name, int number, string hireDate)
        {
            empName = name;
            empID = number;
            empHireDate = hireDate;
        }

        // Mutator functions
        void setEmpName(string name)
        { empName = name; }

        void setEmpID(int number)
        { empID = number; }

        void setEmpHireDate(string hireDate)
        { empHireDate = hireDate; }

        // Accessor functions
        string getEmpName() const
        { return empName; }

        int getEmpID() const
        { return empID; }

        string getEmpDateHired() const
        { return empHireDate; }

        // Friend function
        friend ostream &operator << (ostream &, const Employee &);

        // Virtual function defined in Employee.cpp
        virtual void print(ostream &strm) const;
};

#endif

Employee.cpp


#include "Employee.h"

#include <iomanip>
using std::setw;

#include <iostream>
using std::left;
using std::right;

/* **********************************************************
            Overloaded << operator
    Makes a call to the virtual print function, and sends the
    output to the stream.
   ********************************************************** */

ostream &operator << (ostream &strm, const Employee &obj)
{
    obj.print(strm);
    return strm;
}

/* **********************************************************
               Employee::print() : ostream &
    This function sends formatted employee data to the output
    stream.
   ********************************************************** */

void Employee::print(ostream &strm) const
{
    strm << left << setw(12) << "Employee Name: "
            << right << empName << "\n"
            << left << setw(12) << "Employee ID:   "
            << right << empID << "\n"
            << left << setw(15) << "Hire Date: "
            << right << empHireDate << "\n\n";
}

ProductionWorker.h


#ifndef PRODUCTION_WORKER_H_
#define PRODUCTION_WORKER_H_

#include "Employee.h"

#include <iostream>
using std::ostream;

// ProductionWorker class derived from the Employee class
class ProductionWorker : public Employee
{
    protected:
        int    shiftNumber;                // The shift number (1 = day, 2 = night)
        double hourlyPayRate;            // The hourly pay rate

    public:
        // Default constructor
        ProductionWorker() : Employee()
        {
            shiftNumber = 0;
            hourlyPayRate = 0.0;
        }

        // Parameterized Constructor
        ProductionWorker(string name, int number, string hireDate, int shift, double payRate) :
                  Employee(name, number, hireDate)
        {
            shiftNumber = shift;
            hourlyPayRate = payRate;
        }

        // Mutator functions
        void setShift(int shift)
        { shiftNumber = shift; }

        void setHourlyPayrate(double payRate)
        { hourlyPayRate = payRate; }

        // Accessor functions
        int getShift() const
        { return shiftNumber; }

        double getHourlyPayRate() const
        { return hourlyPayRate; }

        void print(ostream &) const;
};

#endif

ProductionWorker.cpp


#include "ProductionWorker.h"

#include <iomanip>
using std::setprecision;
using std::setw;

#include <iostream>
using std::left;
using std::right;
using std::fixed;

/* **********************************************************
            ProductionWorker::print() : ostream & (overridden)
   ********************************************************** */

void ProductionWorker::print(ostream &strm) const
{
    Employee::print(strm);

    strm << "Shift #" << shiftNumber << ": ";

    shiftNumber == 1 ? strm << setw(16) << right << " Day-Shift\n" :
                                    strm << setw(16) << right << " Night-Shift\n";

    strm << fixed << setprecision(2)
            << left << setw(14) << "Pay Rate: "
            << right << "$ " << hourlyPayRate << "\n";
}

TeamLeader.h


#ifndef TEAM_LEADER_H_
#define TEAM_LEADER_H_

#include "ProductionWorker.h"

// TeamLeader class derived from the ProductionWorker class
class TeamLeader : public ProductionWorker
{
    private:
        double monthlyBonus;                    // Monthly salary bonus
        int    attTrainingHours;                    // Attented training hours

    public:
        const int REQ_TRAINING_HOURS = 75;        // Required hours of traning p.A.

        // Constructor
        TeamLeader() : ProductionWorker()
        {
            monthlyBonus = 0.0;
            attTrainingHours = 0;
        }

        // Parameterized constructor
        TeamLeader(string name, int number, string hireDate, int shift, double payRate,
                      double bonus) :
        ProductionWorker(name, number, hireDate, shift, payRate)
        {
            monthlyBonus = bonus;
            attTrainingHours = 0;
        }

        // Mutator functions
        void setMonthlyBonus(double bonus)
        { monthlyBonus = bonus; }

        void setAttTrainingHours(int attHours)
        { attTrainingHours = attHours; }

        // Accessor functions
        double getMonthlyBonus() const
        { return monthlyBonus; }

        int getAttendedTrainingHours() const
        { return attTrainingHours; }

        int getRemainingTrainingHours() const;   

        // Overridden print function
        void print(ostream &) const;
};

#endif

TeamLeader.cpp


#include "TeamLeader.h"

#include <iomanip>
using std::setw;

#include <iostream>
using std::left;
using std::right;

/* **********************************************************
            TeamLeader::getRemainingTrainingHours()
    This function determines, how many hours of traning are
    left to take for a team leader, in order to fulfill the
    mandatory training requirements.
   ********************************************************** */

int TeamLeader::getRemainingTrainingHours() const
{
    int remainingHours = 0;

    return remainingHours = (REQ_TRAINING_HOURS - attTrainingHours);
}

/* **********************************************************
            TeamLeader::print() : ostream & (overridden)
   ********************************************************** */

void TeamLeader::print(ostream &strm) const
{
    ProductionWorker::print(strm);

    strm << left << setw(14) << "Bonus: "
            << right << "$ " << monthlyBonus << "\n\n"
            << "ANNUAL TRAINING REQUIREMENTS\n\n"
            << "Required:  " << REQ_TRAINING_HOURS << " hrs.\n"
            << "Attended:  " << attTrainingHours << " hrs.\n"
            << "Remaining: " << getRemainingTrainingHours() << " hrs.\n";   
}

TeamLeaderClass.cpp


 #include "TeamLeader.h"

#include <array>
using std::array;

#include <iostream>
using std::cin;
using std::cout;

int main()
{
    // Create a TeamLeader object
    TeamLeader leader("Takahashi Hideki", 92358, "05/07/2014", 1, 39.70, 19.50);
   
    // Create an array of three ProductionWorker objects. Each employee is
    // part of this team leader's team.
    array <ProductionWorker, 3> worker
    {
        ProductionWorker("Hartwood Michael", 23727, "05/07/2016", 1, 14.70),   
        ProductionWorker("Talmar Arman", 54838, "03/03/2005", 1, 29.50),
        ProductionWorker("Clayborn Dolores", 54257, "05/04/2015", 1, 17.50)
    };

    cout << "TAKEUCHI MANUFACTURING CO. - TRACK LOADER ASSEMBLY TEAM\n\n";
    cout << "TEAM LEADER\n\n";
    leader.setAttTrainingHours(35);
    cout << leader;

    cout << "\n\nPRODUCTION TEAM\n\n";
    for (auto workerTeam : worker)
    {
        cout << workerTeam << "\n";
    }
   
    cout << "TAKEUCHI MANUFACTURING CO.\n"
          << "Unrivaled quality, products with a difference,\n"
          << "and fast development responding to the users' needs.";

    cin.get();
    cin.ignore();
    return 0;
}

Example Output:




Friday, January 19, 2018

Programming Challenge 15.2 - ShiftSupervisor Class

Example Files: ShiftSupervisorClass.7z

ShiftSupervisor.h


#include "Employee.h"

// ShiftSupervisor class derived from Employee
class ShiftSupervisor : public Employee
{
    private:
        double annualSalary;                // Annual salary
        double annualBonus;                // Annual bonus

    public:
        // Constructor
        ShiftSupervisor() : Employee()
        {
            annualSalary = 0.0;
            annualBonus = 0.0;
        }

        // Parameterized Constructor
        ShiftSupervisor(string name, int number, string hireDate,
                             double salary) :
                Employee(name, number, hireDate)
        {
            annualSalary = salary;
        }

        // Mutator functions
        void setAnnualSalary(double salary)
        { annualSalary = salary; }

        void setAnnualBonus(double bonus)
        { annualBonus = bonus; }

        void calcAnnualBonus()
        { annualBonus *= annualSalary; }

        // Accessor functions
        double getAnnualSalary() const
        { return annualSalary; }

        double getAnnualBonus() const
        { return annualBonus; }

        double getTotalSalary() const
        { return annualSalary + annualBonus; }
};

#endif

ShiftSupervisorClass.cpp


#include "ShiftSupervisor.h"

#include <iomanip>
using std::setprecision;
using std::setw;

#include <iostream>
using std::cin;
using std::cout;
using std::left;
using std::right;
using std::fixed;

const double BONUS = 0.10;
const int    PRODUCTION_GOAL = 128948;

void getProductionData(ShiftSupervisor &);
bool isGoalMet(const int &);
void outputData(const ShiftSupervisor &);

int main()
{
    // Create a ShiftSupervisor object
    ShiftSupervisor supervisor("Corum J. Irsei", 29835, "05/07/2016", 25760.0);

    cout << "TAKEUCHI MANUFACTURING CO. - FINANCE DEPARTMENT\n\n";
    cout << "Enter number of units produced at this supervisor's line\n"
          << "to determine whether annual salary bonus applies.\n\n";
    getProductionData(supervisor);

    cout << "TAKEUCHI MANUFACTURING CO. - PAYROLL SYSTEM\n\n";
    outputData(supervisor);

   cout << "You are now leaving the Database System ...\n\n";
   cout << "TAKEUCHI MANUFACTURING CO.\n"
        << "Unrivaled quality, products with a difference,\n"
        << "and fast development responding to the users' needs.";

    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
           getProductionData() : const obj &
    This function asks the user to input the number of units
     produced at a supervisor's line. If the production goal
     has been met, the bonus is set and the amount of bonus
     calculated. Otherwise the bonus is set to 0.0.
   ********************************************************** */

void getProductionData(ShiftSupervisor &supervisor)
{
    int unitsTotal = 0;
   
    cout << "Supervisor Name: " << supervisor.getEmpName() << "\n"
          << "Supervisor ID-#: " << supervisor.getEmpID() << "\n";
    cout << "Production Goal: " << PRODUCTION_GOAL << " Units\n\n";

    cout << "Number of units produced: ";
    cin >> unitsTotal;

    while (unitsTotal < 85000 || unitsTotal >= 135000)
    {
        cout << "Number of units produced (Min: 85000, Max: 135000): ";
        cin >> unitsTotal;
    }
    cout << "\n";

    if (isGoalMet(unitsTotal) == true)
    {
        supervisor.setAnnualBonus(BONUS);
        supervisor.calcAnnualBonus();
    }
    else
    {
        supervisor.setAnnualBonus(0.0);
    }
}

/* **********************************************************
           isGoalMet() : const int &
    This function determines whether the production goal has
    been met.
   ********************************************************** */

bool isGoalMet(const int &units)
{
    bool goalMet = false;

    if (units >= PRODUCTION_GOAL)
    {
        cout << "Production Goal Met!\n";
        goalMet = true;
    }

    return goalMet;
}

/* **********************************************************
            outputData() : const obj &
    This function outputs a supervisor's personal data, his
     or her annual salary, annual bonus and total salary.
   ********************************************************** */

void outputData(const ShiftSupervisor &supervisor)
{
    cout << left << setw(12) << "Supervisor: "
          << right << supervisor.getEmpName() << "\n"
          << left << setw(12) << "ID-Number: "
          << right << supervisor.getEmpID() << "\n"
          << left << setw(11) << "Date Hired: "
          << right << supervisor.getEmpDateHired() << "\n\n";

    cout << fixed << setprecision(2);

    cout << left << setw(17) << "Annual Salary: $ "
          << right << supervisor.getAnnualSalary() << "\n";
    cout << left << setw(17) << "Annual Bonus:  $ "
          << right << setw(8) << supervisor.getAnnualBonus() << "\n";
    cout << left << setw(17) << "Total Salary:  $ "
          << right << supervisor.getTotalSalary() << "\n\n";
}


Example Output:





Thursday, January 18, 2018

Programming Challenge 15.1 - Employee and ProductionWorker Classes

Example Files: EmployeeProductionWorker.7z


Employee.h


#ifndef EMPLOYEE_H_
#define EMPLOYEE_H_

#include <string>
using std::string;

class Employee
{
    private:
        string empName;                // Employee name
        int     empID;                    // Employee ID-number
        string empHireDate;            // Employee hire date
   
    public:   
        // Default constructor
        Employee()
        {
            empName = " ";
            empID = 0;
            empHireDate = " ";
        }

        // Parameterized constructor
        Employee(string name, int number, string hireDate)
        {
            empName = name;
            empID = number;
            empHireDate = hireDate;
        }

        // Mutator functions
        void setEmpName(string name)
        { empName = name; }

        void setEmpID(int number)
        { empID = number; }

        void setEmpHireDate(string hireDate)
        { empHireDate = hireDate; }

        // Accessor functions
        string getEmpName() const
        { return empName; }

        int getEmpID() const
        { return empID; }

        string getEmpDateHired() const
        { return empHireDate; }
};

#endif

ProductionWorker.h


#ifndef PRODUCTION_WORKER_H_
#define PRODUCTION_WORKER_H_

#include "Employee.h"

// ProductionWorker class derived from the Employee class
class ProductionWorker : public Employee
{
    private:
        int shiftNumber;                    // The shift number (1 = day, 2 = night)
        double hourlyPayRate;            // The hourly pay rate

    public:
        // Default constructor
        ProductionWorker() : Employee()
        {
            shiftNumber = 0;
            hourlyPayRate = 0.0;
        }

        // Parameterized Constructor - passes name, number and hireDate
        // to the Employee base class
        ProductionWorker(string name, int number, string hireDate, int shift, double payRate) :
                  Employee(name, number, hireDate)
        {
            shiftNumber = shift;
            hourlyPayRate = payRate;
        }

        // Mutator functions
        void setShift(int shift)
        { shiftNumber = shift; }

        void setHourlyPayrate(double payRate)
        { hourlyPayRate = payRate; }

        // Accessor functions
        int getShift() const
        { return shiftNumber; }

        double getHourlyPayRate() const
        { return hourlyPayRate; }
};

#endif

EmployeeProductionWorker.cpp


#include "ProductionWorker.h"

#include <iomanip>
using std::setprecision;
using std::setw;

#include <iostream>
using std::cin;
using std::cout;
using std::left;
using std::right;
using std::fixed;

void getEmployeeData(ProductionWorker &);
void outputData(const ProductionWorker &);

int main()
{
    // Create a ProductionWorker object
    ProductionWorker worker("Jane Moll", 938259, "05/04/1990", 1, 35.80);

    // Create another ProductionWorker object
    ProductionWorker workerOne;

    // Get data for this worker
    cout << "TAKEUCHI MANUFACTURING CO. - EMPLOYEE DATA ENTRY SYSTEM\n\n";
    getEmployeeData(workerOne);

    // Output data
    cout << "\n\nTAKEUCHI MANUFACTURING CO. - EMPLOYEE DATABASE\n\n";
    outputData(worker);
    outputData(workerOne);

    cout << "You are now leaving the Database System ...\n\n";
    cout << "TAKEUCHI MANUFACTURING CO.\n"
          << "Unrivaled quality, products with a difference,\n"
          << "and fast development responding to the users' needs.";

    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
            getEmployeeData() : obj &
    This function gets data for a production worker.
   ********************************************************** */

void getEmployeeData(ProductionWorker &worker)
{
    string name = " ";
    int    number = 0;
    string hireDate = " ";
    int    shift = 0;
    double payRate = 0.0;

    cout << "Enter employee name: ";
    getline(cin, name);
    worker.setEmpName(name);

    cout << "Enter employee ID: ";
    cin >> number;
    worker.setEmpID(number);

    cout << "Enter hire date (mm/dd/yyyy): ";
    cin >> hireDate;
    worker.setEmpHireDate(hireDate);

    cout << "\nEnter shift (1: Day, 2: Night): ";
    cin >> shift;
    worker.setShift(shift);

    cout << "Enter hourly pay rate: $ ";
    cin >> payRate;
    worker.setHourlyPayrate(payRate);
}

/* **********************************************************
            outputData() : const obj &
    This function outputs all data about a production worker.
   ********************************************************** */

void outputData(const ProductionWorker &worker)
{
    cout << left  << setw(12) << "Name: "
          << right << worker.getEmpName() << "\n"
          << left  << setw(12) << "ID-Number: " 
          << right << worker.getEmpID() << "\n"
          << left  << setw(11) << "Date Hired: "
          << right << worker.getEmpDateHired() << "\n\n";

    worker.getShift() == 1 ? cout << "Assigned Shift: Day\n" :
                                     cout << "Assigned Shift: Night\n";
   
    cout << fixed << setprecision(2);
    cout << left << setw(12) << "Payrate: $ "
          << right << worker.getHourlyPayRate() << "\n\n";
}

Example Output:




Monday, January 15, 2018

Stop Cortana on Windows 10

This is just a quick tip, how to get rid of Cortana. I'm writing this entry just because, while coding, the Cortana app, which is deeply routed into the Windows 10 operating system, was constantly accessing, monitoring and whatever else it does, it started to become annoying, lowering my ability to concentrate on the learning process.

There are several tricks out there, that doesn't work, I must add, to stop this application from executing. Among these are the suggested use of regedit, to add a key. Another is to make a call to the Group Policy Editor. There is yet a simpler way to stop Cortana from doing anything. Many Firewall and Security Apps have a feature that allows its users to simply contain an application, or it contains it by itself, if it is a threat to the system.

So, here is the way to do it with Comodo Security Suite. Open it, go to Advanced Settings, HIPS Rules, scroll down to find :\Windows\SystemApps\Microsoft.Windows.Cortona_cw ....\SearchUI.exe
check Use Ruleset and select Contained Application. Do the same for :\Windows\System32\backgroundTaskHost.exe Confirm it, and the Cortona application is unable to execute.

You can check the result when Win-Logo-Key + R, entering taskmgr, to see the tasks that it is gone from there, and any related process with it. 

Since I do not know about other Security Suites, please refer to their respective functions to achieve it. It should be possible with any that offers such functionality as described above with Comodo. If you find that you wish to have Cortana running is beneficial, you can turn it on by reversing the process again.

With this, it is back to do some more learning, about Class Hierarchies.

Saturday, January 13, 2018

A Chapter Closed

It does not happen very often, but it does occasionally; the lack of words to describe how happy this person is, that yet another chapter is history. 

The experience was a mix between utmost interest in the contents of the main chapter, the Challenges were a different story. Not knowing why, but there was a feeling of disconnectedness with many of the early Challenges. There was also lots of repetition. One instance is the Number Class, which is a variation of the Programming Challenge 10.19 - Check Writer program. Another is the Date Class, which had to be modified in this chapter. With Challenge 14.4 and 5 and 6, interest grew, as it allowed me to implement some personal touch to these programs. If you don't know, the names are taken from Alexander McCall Smith's "Mma. Ramotswe" books. Please read them, if you find time! This is something I like doing, as my recurring readers and visitors should already have noticed.

All these were not very challenging, as most of the work was done in previous chapters, which does not mean that all the published solutions are mere copies. No, in most cases it was an opportunity to improve what has been done before. It reflects a growth in knowledge and gives a sense of accomplishement when the new code is indeed better than the old one. 

There was little problem to solve any problem, up to the (Un)challenge 14.9 Feet Inches Modification. This was so unchallenging, that it was done in less than 15 minutes! While in previous chapters this kind of problem would be giving a welcoming breather, it seems that it was not necessary at this chapter, and if it were, than it could have been something more interesting, or a little more challenging at least. 

At a later point, Challenge 11 in particular, this one was really difficult to solve. The task was to write a FeetInches class modification, containing a copy constructor, which allows for the multiplication of two FeetInches objects. The problem was not so much how to write code, but what should the output be? Based on this decision, the formula had to change. As the feet and inches are foreign, I had little knowledge about the expected output. It has taken quite some time to find an online calculator website that offered the functionality of multiplying feet and inches, outputting a result in a way to confirm that my code delivers correct results. This is most important, correct results.  

Truly interesting was the work on the Parking Ticket Simulator and Car Instrument Simulator programs. Both of which I was looking forward to, and indeed, they were rather easy to solve. 14.14 which is the Parking Ticket Simulator was rather difficult in some aspects. Here the problem was more of the nature of how to make the classes interact and do their magic behind the scenes. Most troublesome was to find a way to resolve the dreaded 'circular dependency' issue between the PoliceOfficer and ParkingMeter class. The other was the question how to write the code so, that the classes are not tightly linked to each other. (Or is the correct term coupled?) That was the nature of the problems to face when solving this problem. 

On the whole, this chapter was not too difficult. There was even one solution that felt most complete. That for the Date Class Modification which was Challenge 14.8. It is difficult to express the meaning of 'most complete', the closest is that it feels like one whole, in which every part has its place and everything interacts without any one part - or function, having too much weight or content. It is not perfect, but it is the only good solution for any of the previous two chapters.

Code never feels perfect, in almost no case is this person able to say, it is good enough. Yet, this way of thinking is wrong. While researching the FeetInches problem, I found an article on Nature.com which is all about code sharing. It describes the feeling related to my own code solutions. The important thing to take away is this: "If code is good enough to to do the job, it is good enough to release ..." Of course there are differences, I would release my code anyway in the hopes that it helps someone out there in the world overcome a problem. 

This is a challenge in itself - to overcome the way of thinking that everything has to be perfect, else it has little worth. The other, and I noticed this, is: "Why is this code still so long? It could be much shorter, if only I knew how ...", it is a way of thought that has resurfaced. Maybe it is something that was planted into the mind in the early stages of learning. Without the knowledge about loops, etc., code for a solution was rather long. In particular the Travel Expense program comes to mind. With the introduction of arrays and loops, it may have felt as if code has become shorter, while in fact it had not. Over time the expectation has grown that, with each new tool or part of what C++ has to offer, solutions would become shorter, less code has to be written to accomplish a task.

With time, and more experience, it still will remain an illusion, for now the important thing is what comes next. Chapter 15, the closing chapter about classes, will certainly be most interesting. My hope is, that, once this next chapter will become history, that things become much easier and it is all downhill from that point onward.

This marks the end of this chapter summary, and after a good days rest tomorrow a new chapter will begin. And with this, I wish my readers and visitors that they are able to solve - or overcome all of their challenges whatever they may be. Soon there will be more code, until then, stay well!

Programming Challenge 14.15 - Car Instrument Simulator

Example Files: CarInstrumentSimulator.7z

FuelGauge.h


#ifndef FUEL_GAUGE_H_
#define FUEL_GAUGE_H_

class FuelGauge
{
    private:
        const  int MAX_CAPACITY = 15;        // The max fuel capacity
        static int fuelCapacity;            // Holds the fuel capacity

    public:
        FuelGauge()
        { }

        int getFuelCapacity() const
        { return fuelCapacity; }

        // Overloaded operator functions
        int operator ++(int);                // Postfix ++
        int operator --(int);                // Postfix --
};

#endif

FuelGauge.cpp


#include "FuelGauge.h"

// Definition of fuelCapacity
int FuelGauge::fuelCapacity = 0;

/* **********************************************************
            Overloaded ++ operator
    ********************************************************** */

int FuelGauge::operator ++(int)
{
    if (fuelCapacity < MAX_CAPACITY)
    {
        fuelCapacity++;
    }
    else
    {
        fuelCapacity = MAX_CAPACITY;
    }

    return fuelCapacity;
}

/* **********************************************************
            Overloaded -- operator
   ********************************************************** */

int FuelGauge::operator --(int)
{
    if (fuelCapacity > 0)
    {
        fuelCapacity--;
    }
    else
    {
        fuelCapacity = 0;
    }
   
    return fuelCapacity;
}

Odometer.h


#ifndef ODOMETER_H_
#define ODOMETER_H_

#include "FuelGauge.h"

class Odometer
{
    private:
        const int MAX_MILEAGE = 999999;    // The maximum mileage an odometer can display

        static int mileage;                    // Holding the mileage of a car
        static int milesDriven;                // Counter variable

        // Class object
        FuelGauge gaugeCapacity;

    public:
        Odometer()
        { }

        Odometer(int);

        int getMilesDriven() const
        { return milesDriven; }

        int getCurrentMileage() const
        { return mileage; }

        // Overloaded operator function
        int operator ++(int);                // Postfix ++
};

#endif

Odometer.cpp


#include "Odometer.h"

// Definition of static variables mileage and milesDriven
int Odometer::mileage = 0;
int Odometer::milesDriven = -1;

/* **********************************************************
            Odometer::Odometer() - Constructor : int
   ********************************************************** */

Odometer::Odometer(int miles)
{
    if (mileage >= 0 && mileage <= MAX_MILEAGE)
    {
        mileage = miles;
    }
    else
    {
        miles = 0;
    }
}

/* **********************************************************
            Overloaded Postfix ++
    The postfix operator increments the mileage, and decreases
    the FuelGauge object's current amount of fuel by 1 gallon
    for every 24 miles traveled. If mileage reaches 999999,
    the mileage counter is reset to 0.
   ********************************************************** */

int Odometer::operator ++(int)
{
    if (mileage < MAX_MILEAGE)
    {
        mileage++;

        if (++milesDriven == 24)
        {
            milesDriven = 0;
            gaugeCapacity--;
        }
    }
    else if (mileage >= MAX_MILEAGE)
    {
        mileage = 0;
    }

    return mileage;
}

CarInstrumentSimulator.cpp


#include "FuelGauge.h"
#include "Odometer.h"

#include <iomanip>
using std::left;
using std::right;
using std::setw;

#include <iostream>
using std::cin;
using std::cout;

void timer();
void refillTank(FuelGauge &);
void instrumentSimulator(Odometer &, const FuelGauge &);

int main()
{
    FuelGauge gauge;
    Odometer meter(999998);

    cout << "CAR INSTRUMENT SIMULATOR\n\n";

    refillTank(gauge);
    instrumentSimulator(meter, gauge);

    cin.get();
    cin.ignore();
    return 0;
}

/* **********************************************************
            timer()
    A very simple timer function.
   ********************************************************** */

void timer()
{
    static int seconds = 5;
    static int timeLeft = 0;
    static int counter = 193559599;

    while (timeLeft > 0)
    {
        timeLeft--;
    }

    timeLeft = counter - seconds;
}

/* **********************************************************
            refillTank() : obj &
    This function accepts a FuelGauge object passed to it by
    reference as argument. It simulates a refueling process.
   ********************************************************** */

void refillTank(FuelGauge &gauge)
{
    cout << "Fuel meter E |";

    for (int i = gauge.getFuelCapacity(); i < 15; i++)
    {
        gauge++;
        timer();

        cout << (i + 1) << "*|";
    }

    cout << " F\n\n";
}

/* **********************************************************
            instrumentSimulator() : obj &, const obj &
    This function simulates the main instrument panel of a
    car. It outputs the current mileage driven and current
    gauge capacity.
   ********************************************************** */

void instrumentSimulator(Odometer &meter, const FuelGauge &gauge)
{
    while (gauge.getFuelCapacity() >= 1)
    {
            meter++;

            if (gauge.getFuelCapacity() >= 3)
            {
                cout << "Miles Driven: " << setw(25) << left << meter.getCurrentMileage();
                cout << "Gas Gauge: " << right << gauge.getFuelCapacity() << "\n";
            }
            else if (gauge.getFuelCapacity() > 0 && gauge.getFuelCapacity() <= 3)
            {
                cout << "Miles Driven: " << setw(25) << left << meter.getCurrentMileage();
                cout << "Gas Gauge: "    << right << gauge.getFuelCapacity() << " FUEL LOW!\n";
            }
            else if (gauge.getFuelCapacity() == 0)
            {
                cout << "\nOUT OF FUEL!\n";
            }

            timer();
    }
}

Example Output:


Animation created with ScreenToGif


Thursday, January 11, 2018

Programming Challenge 14.14 - Parking Ticket Simulator

Example Files: ParkingTicketSimulator.7z


ParkedCar.h


#ifndef PARKED_CAR_H_
#define PARKED_CAR_H_

#include <iostream>
using std::ostream;

#include <string>
using std::string;

class ParkedCar
{
    private:
        string make;                        // Car make
        string model;                        // Car model
        string color;                        // Car color
        string plateNumber;                // Car plate number
        int    minutesParked;            // Number of minutes a car is parked

    public:
        ParkedCar()
        { }

        ParkedCar(string, string, string, string, int);

        int getMinutesParked() const
        { return minutesParked; }

        // Friend
        friend ostream &operator << (ostream &, const ParkedCar &);
};

#endif

ParkedCar.cpp


#include "ParkedCar.h"

/* **********************************************************
            ParkedCar::ParkedCar() : Constructor
    Constructor accepting four string objects and an int as
    arguments.
   ********************************************************** */

ParkedCar::ParkedCar(string cMake, string cModel, string cColor, string cLicNum, int minutes)
{
    make = cMake;
    model = cModel;
    color = cColor;
    plateNumber = cLicNum;
    minutesParked = minutes;
}

/* **********************************************************
            Overloaded << operator
   ********************************************************** */

ostream &operator << (ostream &oStrm, const ParkedCar &obj)
{
    return oStrm << "Make:        "           << obj.make             << "\n"
                         << "Model:        "          << obj.model            << "\n"
                         << "Color:        "           << obj.color              << "\n"
                         << "License Number: " << obj.plateNumber << "\n";
}

ParkingMeter.h


#ifndef PARKING_METER_H_
#define PARKING_METER_H_

class ParkingMeter
{
    private:
        int timePurchased;        // The amount of time purchased

    public:
        ParkingMeter()
        { }
       
        ParkingMeter(int minutes)
        { timePurchased = minutes; }

        int getTimePurchased() const
        { return timePurchased; }
};

#endif

PoliceOfficer.h


#ifndef POLICE_OFFICER_H_
#define POLICE_OFFICER_H_

class ParkingTicket;

#include "ParkedCar.h"
#include "ParkingMeter.h"

#include <iostream>
using std::istream;
using std::ostream;

#include <string>
using std::string;

class PoliceOfficer
{
    private:
        string name;                    // Holding the name of an officer
        string badgeNumber;            // Holding the officer's badge number
       
    public:
        PoliceOfficer()
        { }

        PoliceOfficer(string, string);
       
        void setPoliceOfficer(string, string);
        bool isViolator(const ParkingMeter &, const ParkedCar &);
        void issueTicket(const ParkingMeter &, const ParkedCar &);

        // Friends
        friend istream &operator >> (istream &, PoliceOfficer &);
        friend ostream &operator << (ostream &, const PoliceOfficer &);
};

#endif

PoliceOfficer.cpp


#include "PoliceOfficer.h"
#include "ParkingTicket.h"

#include <iostream>
using std::cout;

/* **********************************************************
            PoliceOfficer::PoliceOfficer() - Constructor
    Accepts two string objects as its argument.
   ********************************************************** */

PoliceOfficer::PoliceOfficer(string n, string ID)
{
    setPoliceOfficer(n, ID);
}

/* **********************************************************
            PoliceOfficer::setPoliceOfficer() : string, string
    This function determines whether the string objects passed
    to it are empty. If one or both are empty, a default name
    or badge number is assigned to the appropriate class
    member variables. Else, the values passed to this function
    will be assigned to them.
   ********************************************************** */

void PoliceOfficer::setPoliceOfficer(string n, string ID)
{
    if (!n.empty())
    {
        name = n;
    }
    else
    {
        name = "Haruto Nakayama";
    }

    if (!ID.empty())
    {
        badgeNumber = ID;
    }
    else
    {
        badgeNumber = "NTPD-9284984-RD";
    }
}

/* **********************************************************
            ParkingTicket::isViolator(bool) : const obj &,
                                                         const obj &
    This function accepts two class objects passed to it by
    reference. It compares the time a car is parked to the
    amount of time purchased at the parking meter to determine
    whether the car is legally parked. The result of this
    evaluation is returned from the function.
    ********************************************************** */

bool PoliceOfficer::isViolator(const ParkingMeter &meter, const ParkedCar &car)
{
    bool status = false;

    if (car.getMinutesParked() > meter.getTimePurchased())
    {
        status = true;
    }

    return status;
}

/* **********************************************************
            ParkingTicket::issueTicket() const obj &,
                                                  const obj &
    This function creates a ParkingTicket object and passes to
    its constructor a ParkedCar, an PoliceOfficer, and a
    ParkingMeter object. It then calls the printTicket()
    function of the ParkingTicket class to output the ticket-
    information.
   ********************************************************** */

void PoliceOfficer::issueTicket(const ParkingMeter &meter, const ParkedCar &car)
{
    ParkingTicket tempTicket(car, *this, meter);

    tempTicket.printTicket();
}

/* **********************************************************
            Overloaded >> operator
   ********************************************************** */

istream &operator >> (istream &iStrm, PoliceOfficer &obj)
{
    cout << "Officer name: ";
    getline(iStrm, obj.name);
    cout << "Officer ID:   ";
    getline(iStrm, obj.badgeNumber);

    obj.setPoliceOfficer(obj.name, obj.badgeNumber);

    return iStrm;
}

/* **********************************************************
            Overloaded << operator
   ********************************************************** */

ostream &operator << (ostream &oStrm, const PoliceOfficer &obj)
{
    return oStrm << "Officer Name: " << obj.name << "\n"
                         << "Officer ID:   " << obj.badgeNumber << "\n";
}

ParkingTicket.h


#ifndef PARKING_TICKET_H_
#define PARKING_TICKET_H_

#include "PoliceOfficer.h"

class ParkingTicket
{
    private:   
        const double BASE_FINE   = 25.0;        // Base fine for the first hour or part of an hour
        const double HOURLY_FINE = 10.0;        // Additional fine for every additional hour or part of an hour

        double fine;                                // The amount of fine to be paid
        double hourlyFine;                     // The amount of additional fine to be paid

        // class objects
        PoliceOfficer issuer;
        ParkedCar violator;
        ParkingMeter parkingMeter;

    public:
        ParkingTicket()
        { }

        ParkingTicket(const ParkedCar &, const PoliceOfficer &, const ParkingMeter &);

        void calcFine();
        void printTicket();

        double getFine() const
        { return fine; }

        double getHourlyFine() const
        { return hourlyFine; }
};

#endif

ParkingTicket.cpp


#include "ParkingTicket.h"

#include <iomanip>
using std::cout;
using std::setprecision;

#include <iostream>
using std::fixed;

/* **********************************************************
            ParkingTicket::ParkingTicket()
    Constructor accepting three class objects passed to it by
    reference.
   ********************************************************** */

ParkingTicket::ParkingTicket(const ParkedCar &car, const PoliceOfficer &officer, const ParkingMeter &meter)
{
    violator = car;
    parkingMeter = meter;
    issuer = officer;

    calcFine();
    printTicket();
}

/* **********************************************************
            ParkingTicket::calcFine()
    This function calculates the amount of fine. If the amount
    of time is lower than two hours, the base fine is assigned
    to the fine class member variable. Else, the fine and
    additional fine is calculated and assigned to the class
    member variables fine and addFine.
   ********************************************************** */

void ParkingTicket::calcFine()
{
    int overTime = (1 + (violator.getMinutesParked() - parkingMeter.getTimePurchased()) / 60);

    if (overTime < 2)
    {
        fine = BASE_FINE;
    }
    else
    {
        fine = BASE_FINE + (HOURLY_FINE * overTime);
        hourlyFine = fine - BASE_FINE;
    }
}

/* **********************************************************
            ParkingTicket::printTicket()
    This function outputs a traffic-ticket with all relevant
    information.
   ********************************************************** */

void ParkingTicket::printTicket()
{
    cout << "NEO TOKYO CHIYODA WARD - PARKING VIOLATION NOTICE\n\n";
    cout << "Allowed parking time exceeded\n\n";
    cout << "Minutes Parked:    " << violator.getMinutesParked() << "\n";
    cout << "Minutes Purchased: " << parkingMeter.getTimePurchased() << "\n\n";
   
    cout << "REPORTING PATROL OFFICER\n";
    cout << "------------------------\n\n";
    cout << issuer << "\n";

    cout << "VIOLATOR\n";
    cout << "--------\n";
    cout << violator << "\n";

    cout << fixed << setprecision(2);

    cout << "FINE\n";
    cout << "----\n";

    if (getFine() == BASE_FINE)
    {
        cout << "Base Fine:   NTY " << BASE_FINE << "\n";
    }
    else
    {
        cout << "Base Fine:   NTY " << BASE_FINE << " +\n";
        cout << "Hourly Fine: NTY " << getHourlyFine() << "\n";
    }
    cout << "------------------------\n";
    cout << "Total Fine:  NTY " << getFine() << "\n\n\n";
}

ParkingTicketSimulator.cpp


#include "PoliceOfficer.h"
#include "ParkedCar.h"
#include "ParkingMeter.h"

#include <iostream>
using std::cin;
using std::cout;

#include <vector>
using std::vector;

int main()
{
    int numTicketsIssued = 0;

    vector<ParkedCar> car { ParkedCar("Porsche", "Cayenne", "Cyan", "NT-923865", 480),
                                   ParkedCar("Toyota", "Vellfire 2.5 X MPV", "Black", "NT-239575", 25),
                                   ParkedCar("Mazda", "2 G115 Revolution Top", "Machine Gray", "NT-392755", 61),
                                   ParkedCar("Alfa", "Giulietta Exclusive", "Nero Etna", "NT-23975", 55) };

    vector<ParkingMeter> meter { ParkingMeter(120),
                                          ParkingMeter(30),
                                          ParkingMeter(60),
                                          ParkingMeter(60) };

    PoliceOfficer officer;

    cout << "NEO TOKYO CHIYODA WARD - PARKING TICKET SIMULATOR\n\n";
    cout << "Assign Patrol Officer\n\n";
    cin >> officer;
    cout << "\n";

    for (size_t idx = 0; idx < meter.size(); idx++)
    {
        if (officer.isViolator(meter[idx], car[idx]) == true)
        {
            officer.issueTicket(meter[idx], car[idx]);
            numTicketsIssued++;
        }
    }

    if (numTicketsIssued == 0)
    {
        cout << "Chiyoda Ward's streets are safe!\n"
              << "There have been no parking violation reports.";
    }
   
    cin.get();
    cin.ignore();
    return 0;
}

Example Output: