Month: December 2022

Improving your Classes

Exercise 1: Extra Constructors

In this exercise we are going to add extra constructors. But first we do a little experiment.

In the Point class constructor and destructor, add some code that displays some text.

In the main program, make sure you use the Distance() function to calculate the distance

between two points. Run the program and count how many times the constructor and

destructor are called. Are they the same?

Now add a copy constructor to the Point class that also displays some text. Also add a

constructor that accepts x- and y-coordinates so you can create a point with the right values

without using the set functions. Use this constructor to create the point from the user input.

Run the program again and count the number of times the constructors and destructor are

called. Is the copy constructor called and is the number of constructor calls now the same as

the number of destructor calls?

We can derive two things from these results:

  1. When calling the Distance() function, the input point is copied (call by value).
  2. You will get the copy constructor ‘for free’ when you do not create one yourself.

Exercise 2: Pass by Reference

In the previous exercise, you saw that the point passed to the Distance() method was copied.

Since creating a copy is unnecessary in this case, change this function so that it passes the

input point “by reference” so that no copy is made. Pass it as “const reference” to make it

impossible to change the input point from within the Distance() function.

Run the program again. It should call the copy constructor fewer times than before.

Also test if you can change the input point in the Distance() function. This should result in a

compiler error.

Exercise 3: Function Overloading

Previously you saw that there could be more than one constructor as long as the input

arguments are different. You can do the same for normal member functions. Thus you can

rename the DistanceOrigin() function to Distance(). Also you can rename

the SetX() andGetX() functions to just X(). The same is true for the setter and getter of the y

coordinate.

Exercise 4: Const Functions

In the test program create a const point and try to set the x-coordinate:

const Point cp(1.5, 3.9);

cp.X(0.3);

Compile the program. Did you get a compiler error? It should give a compiler error because

you try to change a const object.Now replace the line that changes the x-coordinate to code that reads the x-coordinate:

cout<<cp.X()<<endl;

Compile the program again. You will see that is still gives a compiler error even while

retrieving the x-coordinate does not change the point object. This is because the compiler

does not know that the function does not change anything. So we need to mark the x

coordinate getter as const by making it a const function. Do this also for the y-coordinate

getter and the Distance() and ToString() functions because these don’t change the point

object as well.

Recompile the application. It should now work.

Exercise 5: Line Class

In the final exercise for this chapter we are going to create a Line class. The Line class has a

start- and an end-point. So the Line class should have two Point objects as data members.

This mechanism is called “composition”. See also Figure 3.

Give the Line class the following functionality:

  • Default constructor (set the points to 0, 0).
  • Constructor with a start- and end-point.
  • Copy constructor.
  • Destructor.
  • Overloaded getters for the start- and end-point.
  • Overloaded setters for the start- and end-point.
  • A ToString() function that returns a description of the line.
  • A Length() function that returns the length of the line. Note that you can use the

distance function on the embeddedPoint objects to calculate the length. This

mechanism is called “delegation”.

Use const arguments, const functions and pass objects by reference where applicable.

 

Exercise 5: Line Class

In the final exercise for this chapter we are going to create a Line class. The Line class has a

start- and an end-point. So the Line class should have two Point objects as data members.

This mechanism is called “composition”. See also Figure 3.

Give the Line class the following functionality:

  • Default constructor (set the points to 0, 0).
  • Constructor with a start- and end-point.
  • Copy constructor.
  • Destructor.
  • Overloaded getters for the start- and end-point.
  • Overloaded setters for the start- and end-point.
  • A ToString() function that returns a description of the line.
  • A Length() function that returns the length of the line. Note that you can use the

distance function on the embeddedPoint objects to calculate the length. This

mechanism is called “delegation”.

Use const arguments, const functions and pass objects by reference where applicable.

The Class Concept

Exercise 1: Point Class

Now you must use C++ syntax!!

In this exercise we start creating a Point class with and x- and y-coordinates. This class will

be extended in further exercises.

In Visual Studio, create an empty “Win32 Console Application”. If you don’t check the

“Empty Project” checkbox in the wizard, Visual Studio will generate code for you and will

set the “use pre-compiled headers” on… Pre-compiled headers, which are a Visual Studio

specific option, require special attention in your code and file settings so that is why an empty

project is more appropriate.

First add a header file for the Point class with private members for the x- and y-coordinates.

Do not forget to add the #ifndef/#define/#endif statements to avoid multiple inclusion.

Also make sure you make to following public functionality (see also Figure 1):

  • Default constructor.
  • Destructor.
  • Getter functions for the x- and y-coordinates (GetX() and GetY() functions).
  • Settter functions for the x- and y-coordinates (SetX() and SetY() functions).
  • A ToString() that returns a string description of the point. Use the std::string class as

return type.

+GetX()

+GetY()

+SetX()

+SetY()

+ToString()

-m_x

-m_y

Point

Figure 1: Point Class

Next create the source file that implements the Point class defined in the header file. The

source file must include the header file.

Making the string in the ToString() function, requires conversion of the double coordinates to

a string. Easiest is to use a std::stringstream object and the standard stream operators (as

with iostream) to create the string. This requires the “sstream” header file. Use

the str() function to retrieve the string from the string buffer. The output can be like:

“Point(1.5, 3.9)”

Finally create a test program (separate source file with a main() function) for the Point class.

It should do the following things:

  • Include the point header file. • Ask the user for the x- and y-coordinates using the std::cin object (needs the

“iostream” header file).

  • Then create a Point object using the default constructor.
  • Set the coordinates entered by the user using the setter functions.
  • Print the description of the point returned by the ToString() function.
  • Print the point coordinates using the get functions.

Exercise 2: Distance Functions

In this exercise we are going to add distance functions to the Point class. The distance

functions have the following signature:

double DistanceOrigin(); // Calculate the distance to the origin (0, 0).

double Distance(Point p); // Calculate the distance between two points.

Add the definitions to the header file and implement the functions in the source file. Use

the std::sqrt() function from the “cmath” header file to implement the Pythagoras algorithm.

Extend the main program to print the distance between the origin and another point and test

+GetX()

+GetY()

+SetX()

+SetY()

+ToString()

+DistanceOrigin()

+Distance()

Point

-m_x

-m_y

Figure 2: Point Class with Distance() functions

Input and Output

Exercise 1

Create a C-program that reads the characters from the keyboard and shows them on

screen (the inputted characters should only be displayed when the user hits ‘enter’, line

by line).

When ^A is entered, the program must end properly. Then the following message will

appear: “CTRL + A is a correct ending.”

Tip: getchar() reads and putchar() writes the type int. The value of ^A is 1.

Exercise 2

Alter the last program of exercise 1 in such a way that the output doesn’t go to the screen

but is written to a file. The file to write to must be specified by the user.

Structures

Write a C-program that prints the contents of a struct called Article. An Article has the

following characteristics:

  • Article number
  • Quantity
  • Description (20 characters)

The test program must create an Article of which the contents are assigned at

initialization level.

Printing the Article is done with a Print() function. This function gets the address of the

structure as a parameter.

Tip: Suppose that p is the pointer to the structure. It will allow the fields to be printed

by (*p).fieldname or p->fieldname.

Pointers and Arrays

Exercise 1

Try to create a function Swap(). This function must exchange the value of two variables.

For example: if i=123 and j=456, then i=456 and j=123 after the Swap() function has

been called. The variables i and j are declared, initialised and printed in the

function main(). This problem can be solved by using pointers as arguments for

the Swap()function.

Exercise 2

The following program reads a string with a 30 character maximum. Implement

the Length() function. The function Length() must determine the length of the string.

Give Length() the address of the array as argument.

Note: your Length() function should be similar to the built-in strlen() function so your

job is to mimic that function without using it.

EOF is used in the function main(). This means End-of-File and is discussed later on in

this document.

In DOS, EOF can be entered by the key combination Ctrl-z (often written as ^Z). With

^Z (Say: control Z) is meant pressing the control-key and the z-key simultaneously.

The Preprocessor

Write a C-program that contains two print macro calls. The first prints the variable a, the

second prints the variables a and b. Printing happens by the use of the PRINT1 and

PRINT2 macros that accept arguments. These macros must be defined in an include-file.

The variables a and b gets their value in the function main().

Name the program “Macro.c” and the include-file “Defs.h”. Don’t forget to implement

the mechanism to avoid multiple inclusion of the header file.

Artificial Intelligence

The objective of this homework is to build a hand gesture classififier for sign language. We will be using

Google Colaboratory to train our model (set up instructions at the end). The dataset will be in the form of

csv fifiles, where each row represents one image and its true label.

We have provided the skeleton code to read in the training and testing datasets. Before you begin coding, go

through the provided code and try to fifigure out what each function is responsible for. Most of the functionalities are

implemented in the SignLanguage class. Below are brief descriptions of each function and what is expected of you.

  • create model(self): You will generate a keras sequential mode here. Make sure to set the self.model

variable with your compiled sequential model.

  • prepare data(self, images, labels): Mainly this splits the data into training and validation sets. You may

choose to normalize or downsample your data here, as well.

  • train(self, batch size, epochs, verbose): This method invokes the training of the model. Make sure to

return the generated history object. Your model will be trained for a max of 50 epochs during grading. Make

sure you are using the input parameters (batch size, epochs, verbose)

  • predict(self, data): This method will be invoked with the test images. Make sure to downsample/resize the

test images the same way as the training images, and return a list of predictions.

  • visualize data(self, data): Nothing to do here. This is solely to help you visualize the type of data you are

dealing with.

  • visualize accuracy(self, history): Nothing to do here. It plots out the accuracy improvement over training

time

Opengl Project

Introduction This project requires you to draw something fun in 3D. It must be your own creation. You can use pre-canned 3D objects, such as the ones that GLUT provides or OBJ files, but in addition to your own, not instead of. You must create your own geometry. You can explicitly list your own 3D coordinates, or you can use equations and define the 3D shapes procedurally. You must have at least 100 x-y-z coordinates. These can be divided up among multiple of your objects. The scene must have 3D thickness, nothing that is completely planar. You must use at least 5 different colors. The 3D rotation and scaling from the sample program must still be working.

Prefix

You are given n strings s1, s2, · · · , sn and q queries. In i th query, you are given a string ti , please find

out how many strings in s1, s2, · · · , sn begins with ti .

Football Match

While the FIFA World Cup is being held in Qatar, BLGG is organizing a football tournament in LGU,

too.

There are n teams in this tournament, numbered from 1 to n. Each team has its popularity, and the

popularity of team i is ai . A match between i and j will gain ai × aj MOD M attractions.

When a football team loses a match, it will be eliminated from the tournament. At the end, the team

left standing will be the champion of this tournament.

BLGG is wondering that what the maximum sum of the attractions of the (n 1) matches.