The code consists of the following files:
-
Rectangle.handRectangle.cpp: These files define theRectangleclass, which represents a zone in the environment. It provides functions to set and get the zone's properties and check if a point is inside the zone or within a certain range of the zone. -
Robot.handRobot.cpp: These files define theRobotclass, which represents the industrial robot. It contains functions to set and get the robot's path and add points to the path. -
Point.h: This file defines thePointstructure, which represents a 2D point withxandycoordinates. -
main.cpp: This file contains the main entry point of the program. It includes the necessary header files, defines theinitializeZonesAndPathfunction, and implements the main algorithm of the program in themain()function.
To compile and run the program, follow these steps:
-
Make sure you have a C++ compiler (such as GCC or Clang) installed on your system.
-
Download or clone the code files to your local machine.
-
Open a terminal or command prompt and navigate to the directory containing the code files.
-
Compile the code using the following command:
g++ main.cpp Robot.cpp Rectangle.cpp -o program
This command compiles the source files and creates an executable file named program.
-
Run the program by executing the generated executable:
./program
The program will read the input file (input.txt by default), process the robot's path and the zones, and log the occurrences where the robot interacts with the zones.
Note: If you want to use a different input file, update the filename variable in the main() function of main.cpp before compiling.
The provided C++ code reads input from a text file, processes the data, and performs operations based on the input. Here is a step-by-step explanation of how the algorithm works:
-
File Initialization:
- Include necessary header files and define the
initializeZonesAndPathfunction. - Open the specified file using an
std::ifstreamobject namedinputFile. If the file fails to open, an exception is thrown. - Declare a string variable named
lineto store each line read from the file.
- Include necessary header files and define the
-
Lambda Function:
- Define a lambda function named
readNextNonEmptyLineto handle the task of reading the next non-empty line from the file. - Use a
whileloop withstd::getlineto read lines until a non-empty line is encountered. - The lambda function returns
trueif a non-empty line is found andfalseif there are no more lines to read.
- Define a lambda function named
-
Path Extraction:
- Call the
readNextNonEmptyLinefunction to check for a non-empty line. - If a non-empty line is found:
- Process the line to extract pairs of
xandycoordinates using anstd::istringstreamobject namediss. - Add the extracted coordinates to the
Robotobject's path using theaddPointToPathmethod.
- Process the line to extract pairs of
- If no non-empty line is found for the path information, an exception is thrown.
- Call the
-
Zone Extraction:
- Call the
readNextNonEmptyLinefunction to check for a non-empty line. - If a non-empty line is found:
- Process the line to extract the zone name,
xandycoordinates, width, and height using theissobject. - Create
Rectangleobjects with the extracted information and add them to thezonesvector.
- Process the line to extract the zone name,
- If there is an issue with the input format (e.g., incorrect syntax or missing values), an exception is thrown.
- Call the
-
File Closing:
- Once all the lines have been processed, close the input file.
-
Main Function:
- Create a
Robotobject namedrobot, declare a filename variable, and initialize an empty vector ofRectangleobjects namedzones. - Call the
initializeZonesAndPathfunction, passing the filename,zonesvector, androbotobject as arguments. - This function reads the input file and populates the
robotobject with path information and thezonesvector with zone information.
- Create a
-
Flag Initialization:
- Create a vector of characters named
flagswith the same size as thezonesvector. - This vector will be used to track the status of each zone.
- Create a vector of characters named
-
Zone Tracking:
How it works: If the point is not within a 1-meter range, keep the flag as false. Once it enters the 1-meter range, check the flag. If the flag is false, it means the point was not previously in the range, so print "entering". If the flag is true, it means the point was already inside the zone, so print "leaving". If the point is inside the zone, print "inside" and set/keep the flag true in order to track its state when the point is outside the zone but within the 1-meter range.
- Initialize an integer variable named
countto zero. It will keep track of the index of the current zone while iterating over thezonesvector. - Enter a nested loop:
- The outer loop iterates over each point in the
robotobject's path. - The inner loop iterates over each
Rectangleobject in thezonesvector. - For each point and zone pair:
- Check if the point is within the range of the zone by calling the
checkIfPointWithinRangemethod of theRectangleobject. - If the point is within the zone's range:
- Check if the point is inside the zone by calling the
checkIfPointInZonemethod. - If the point is inside the zone:
- Print a message indicating that the point is inside the current zone's name.
- Set the corresponding flag in the
flagsvector to true if it is not already set.
- If the point is outside the zone but within its range:
- Check the corresponding flag in the
flagsvector. - If the flag is set, print a message indicating that the point is exiting the current zone.
- If the flag is not set, print a message indicating that the point is about to enter the current zone.
- Check the corresponding flag in the
- Check if the point is inside the zone by calling the
- If the point is outside the zone's range, reset the corresponding flag in the
flagsvector to false. - Increment the
countvariable to move to the next zone.
- Check if the point is within the range of the zone by calling the
- After processing all points for a given zone, reset the
countvariable to zero and print a newline character.
- The outer loop iterates over each point in the
- Initialize an integer variable named
-
Exception Handling:
- Use a
try-catchblock to catch any exceptions thrown during the execution of the program. - If an exception occurs, print an error message indicating the exception's details.
- Use a
This algorithm utilizes a lambda function, readNextNonEmptyLine, to handle the repetitive task of reading the next non-empty line from the input file. In SecondVersion branch, I added the use of smart pointers.
-
Lambda Functions
-
Range-based for loop
-
Auto type inference
I used the auto keyword to automatically deduce the type of the variable in
zonesvector:std::unique_ptr<Rectangle>. -
Initializer Lists
Initialize objects using braced initializer lists ({}) for uniform and concise initialization.
-
Using std::optional
Instead of using flags to represent the state of zones, I used
std::optionalto provide a more expressive and type-safe representation. It allows me to express the possibility of having a value (trueorfalse) or having no value (std::nullopt). -
Smart Pointers
In this modified code, the zones vector is now a vector of
std::unique_ptr<Rectangle>. TheinitializeZonesAndPathfunction usesstd::make_uniqueto dynamically allocate Rectangle objects and stores them as unique pointers in the zones vector. The deallocation of memory for the Rectangle objects is automatically handled by thestd::unique_ptrwhen the vector goes out of scope.In the code, I made the following changes:
-
Changed the
zonesvector tostd::vector<std::unique_ptr<Rectangle>> zonesto store Rectangle objects asstd::unique_ptr. It ensures that the dynamically allocated objects are properly deallocated when they are no longer needed. By usingstd::unique_ptr, I avoid the need to manually call delete on the objects. -
Modified the
initializeZonesAndPathfunction to usestd::make_unique: Instead of directly creating Rectangle objects and adding them to the zones vector, I usedstd::make_uniqueto store them asstd::unique_ptr<Rectangle>. -
Changed the iteration over zones to use
const auto& z: When iterating over the zones vector, I usedconst auto& zinstead of copying thestd::unique_ptr<Rectangle>objects. This avoids unnecessary copying of the smart pointers and improves performance. -
In the previous code,
z.checkIfPointWithinRange(p)was used to call the member functioncheckIfPointWithinRangeon the Rectangle object z. However, in the modified code that uses smart pointers, we store Rectangle objects asstd::unique_ptr<Rectangle>in the zones vector. To access the member functions of the Rectangle objects through the smart pointer, we use the arrow operator(->). The arrow operator is used to dereference the smart pointer and access the member functions. It is equivalent to (*z).checkIfPointWithinRange(p), where the * operator is used to dereference the smart pointer and access the underlying object.
-