This blog serves as a place for me where I can occasionally dump bits of content from my brain. Feel free to browse.

Cyber Chat – Artificial Intelligence Chat-bot

It’s my new project in C++.

About Cyber Chat:

Cyber Chat is an Artificial Intelligence chatter-bot that interacts with the user in simple English language and can simulate a conversation. It has a repository or knowledge-base of patterns, which are matched with the input to give the best possible reply. More generally, the technique which is used in the knowledge-base to represent the Cyber Chat knowledge is known as “Case Base Reasoning” or CBR.

It has a large database consisting of 22 files.

- Download Link
- Sample Chat-log


C++ – Hanoi Towers Solution

Please don’t ask me how this code works! :)

#include <iostream>
 
using namespace std;
 
void hanoi(int n, char source, char intermediate, char destination) {
 
    if (n > 0) {
        hanoi(n - 1, source, destination, intermediate);
        cout << " - Moving disk " << n << " from " << source << " to " << destination << endl;
        hanoi(n - 1, intermediate, source, destination);
    }
 
}
 
int main() {
    int n;
    cout << "Enter the no. of disks: "; cin >> n;
    hanoi(n, 'A', 'B', 'C');
    return 0;
}

C++ – Quadratic Equation Solver

Functions:

checkRoots()
calculateRoots()

#include <iostream>
#include <iomanip>
#include <math.h>
 
using namespace std;
 
int checkRoots(double A, double B, double C) {
 
	int D = pow(B, 2) - 4 * A * C;
 
	if (D > 0) {
		return 0;
	}
	else {
		return D;
	}
 
}
 
void calculateRoots(double A, double B, double C) {
 
	double x1, x2;
 
	x1 = (- B + sqrt(pow(B, 2) - 4 * A * C)) / (2 * A);
	x2 = (- B - sqrt(pow(B, 2) - 4 * A * C)) / (2 * A);
 
	if (x1 != x2) {
		cout << "1. X = " << setprecision(5) << x1 << endl;
		cout << "2. X = " << setprecision(5) << x2 << endl;
	}
	else {
		cout << "X = " << setprecision(5) << x1 << endl;
	}
}
 
int main() {
 
	double A, B, C;
 
	cout << "Quadratic Equation Solver" << endl << endl;
 
	cout << "A = "; cin >> A;
	cout << "B = "; cin >> B;
	cout << "C = "; cin >> C;
 
	int result = checkRoots(A, B, C);
 
	cout << endl;
 
	if (result == 0) {
		calculateRoots(A, B, C);
	}
	else {
		cout << "Complex Roots" << endl;
		cout << "[Discriminant = " << result << "]" << endl;
	}
 
	return 0;
}

Astericks Program Code – Lab #5

Change ROWS variable to the number of rows you want to print.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <iomanip> // for the setw() manipulator
 
using namespace std;
 
int main() {
 
	int ROWS = 4; // Yeah in capitals, just to make it look cool!
	for (int x=1; x < ROWS + 1; x++) {
		cout << setw (ROWS + 1 - x);
		for (int i=1; i <= x * 2 - 1; i++) cout << "*";
		cout << endl;
	}
 
	for (x=ROWS-1; x > 0; x--) {
		cout << setw (ROWS + 1 - x);
		for (int i=1; i <= x * 2 - 1; i++) cout << "*";
		cout << endl;
	}
 
	return 0;
	// This comment is self explanatory... no need to explain :)
}

Output:



C++ List All Files in a Directory

If you need to do a certain task on all files or folders in a directory, the following code does the job. The following function recursively calls itself for all contained subfolders and prints all the files found. Note that this code will only run on Windows operating system as it uses Win32 API’s, namely FindFirstFile, FindNextFile and FindClose.

GetAllFiles() is called with the path of the base folder from where you want to start the enumeration.

Example Usage: GetAllFiles(“D:”);

Required Headers: <string> and <windows.h>


void GetAllFiles( string sPath )
{
    WIN32_FIND_DATA FindFileData;
    string sTmpPath = sPath;
    sTmpPath += "\\*.*";

    HANDLE hFind = FindFirstFile( sTmpPath.c_str(), &FindFileData );

    if ( hFind == INVALID_HANDLE_VALUE )
        return;
    else {
        do {
            if ( ( FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) {
		// if directory:
                if ( strcmp(".", FindFileData.cFileName ) && strcmp("..", FindFileData.cFileName) ) {
		    sTmpPath = sPath;
                    sTmpPath += "\\";
		    sTmpPath += FindFileData.cFileName;
                    GetAllFiles( sTmpPath.c_str() );
                }
            }
            else // if file:
            {
		sTmpPath = sPath;
                sTmpPath += "\\";
		sTmpPath += FindFileData.cFileName;
                cout << sTmpPath << endl;
            }
        } while ( FindNextFile( hFind, &FindFileData) != 0 );

        FindClose( hFind );
    }
    return;
}

C++ Bitwise Operations

Awhile ago, I was working on to create a bit array in order to compactly store individual boolean values. So that a typical 1 byte could be used to store an array of 8 boolean values (since each boolean value requires only one bit in order to be represented, i.e 0 or 1). This is a much better strategy, since on the other hand if we use simple array for storing 8 boolean values, it would take 8 bytes in memory instead of just one.

I created a class for this purpose which implemented this functionality and provided a clean interface to the user for using that array. However, I came to know later that such type of optimization is already done internally by the vector<bool> standard library, so it’s not particularly useful to code it ourselves.

I coded two functions for the purpose of setting individual bits ON or OFF in a byte. These functions perform the basic ON and OFF bit-wise operations and checking the status of a bit. So I thought it would be useful to share them with others too.

Functions for setting a particular bit ON or OFF in a byte:

Below is the code for the functions. This will give you some idea of how bit-wise operations can be used in C++ to perform some meaningful operation.

These functions do not return any values.

void setBitOn(unsigned int &value, int num) {
	const int SHIFT = num;
	const unsigned int MASK = 1 << SHIFT;
	value = value | MASK;
}
 
void setBitOff(unsigned int &value, int num) {
	const int SHIFT = num;
	const unsigned int MASK = 1 << SHIFT;
	value = value & (~MASK);
}

Function to check if a particular bit is ON or OFF:

bool checkBit(unsigned int value, int num) {
	const int SHIFT = num;
	const unsigned int MASK = 1 << SHIFT;
	return ((value | MASK) == value ? true : false);
}

Parameters defined:

In these functions, int num parameter is the offset of the bit which is to be reset. Thus num = 0 would be the right-most bit in the byte.
While, value is an unsigned int on which the operation is to be performed.

Example usage of the functions:

int main() {
 
	unsigned int x = 244;
	setBitOn(x, 0);   // set right-most bit to 1
	for (int i = 7; i >=0; i--) {
		cout << checkBit(x, i) ;
	}
	cout << endl;
	return 0;
 
}

Output of the above code would be: 11110101. Note that the binary of 244 is 11110100.

That’s all. I hope you learnt something from my code.

Happy coding, :)
Hassan


C++ Learning Ebooks

C++ How to program, By Deitel & Deitel (5th Edition)

ISBN: 0-13-185757-6 © 2005
Author: Dr. Harvey Deitel & Paul Deitel

Filesize: 10.8 MB

Deitel’s C++ How to Program is a C++ teaching book included in our course. Although current edition of the book is seventh we’ll be using the 5th one, and so I’ve uploaded it here. The zip file also contains the source-code of the examples provided in the book.

The Deitels’ C++ How to Program is the most comprehensive, practical introduction to C++ ever published — with hundreds of hands-on exercises, roughly 250 complete programs written and documented for easy learning, and exceptional insight into good programming practices, maximizing performance, avoiding errors, debugging, and testing.

Plus, this book has thousands of cute “bumble bees” as well. :P

Download Link

The C++ Programming Language (Special 3rd Edition)

ISBN: 0-201-70073-5
Author: Bjarne Stroustrup

Filesize: 3.38 MB

A book by the creator of C++, Bjarne Stroustrup. This book presents the full specification for the C++ language and the design of its standard library. This book is a must have for those seeking to do some serious programming in C++.

While The C++ Programming Language is not a C++ tutorial, strictly speaking, anyone learning the language, especially those with C background, will greatly benefit from the clear presentation of all its elements. It is impossible to overstate the importance of this book for anyone who is serious about using and learning C++.

Download Link

“I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone.” – Bjarne Stroutsup

Other C++ Reference Books:

  • Wrox Press C++ Tutorial

    Although this book comes packed with the MS Visual C++ software, I’ve uploaded it anyway.


HA Computer Dictionary

HA Computer Dictionary is a comprehensive dictionary of about 10,000 computer related terms and abbreviations. The dictionary includes terms drawn from a wide variety of topics relevant to computer users, including software, hardware, networking and so on.

You can download this software from Download.com. Here is the link:
http://download.cnet.com/HA-Computer-Dictionary/3000-2051_4-10885269.html


Bomberman Game

Here is a very nice clone of classic old game: Bomberman. I developed this game about two years ago, but I just remembered it today so thought to post it on my blog. This is my first real application in VB.NET.

Download the Game
Download Source Code

Note: This game requires .NET Framework to be installed on your computer in order to run.


Login to website using VB.NET

The example below uses HttpWebRequest and HttpWebResponse classes to log in to Facebook.

Dim cookieJar As New Net.CookieContainer()
Dim request As Net.HttpWebRequest
Dim response As Net.HttpWebResponse
Dim strURL As String
 
Try
     'Get Cookies
     strURL = "https://login.facebook.com/login.php"
     request = Net.HttpWebRequest.Create(strURL)
     request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3"
     request.Method = "GET"
     request.CookieContainer = cookieJar
     response = request.GetResponse()
 
     For Each tempCookie As Net.Cookie In response.Cookies
            cookieJar.Add(tempCookie)
     Next
 
     'Send the post data now
     request = Net.HttpWebRequest.Create(strURL)
     request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3"
     request.Method = "POST"
     request.AllowAutoRedirect = True
     request.CookieContainer = cookieJar
 
     Dim writer As StreamWriter = New StreamWriter(request.GetRequestStream())
     writer.Write("email=username&pass=password")
     writer.Close()
     response = request.GetResponse()
 
     'Get the data from the page
     Dim stream As StreamReader = New StreamReader(response.GetResponseStream())
     Dim data As String = stream.ReadToEnd()
     response.Close()
 
     If data.Contains("<title>Facebook") = True Then
            'LOGGED IN SUCCESSFULLY
     End If
 
Catch ex As Exception
     MsgBox(ex.Message)
End Try

Now, here is some explanation:

Get Cookies

The following block of code gets all the cookies from Facebook and stores them in a collection. These cookies are returned upon visiting the webpage: https://login.facebook.com/login.php. Getting the cookies is very important, because they must be passed back to the webpage when you are going to login.

For Each tempCookie As Net.Cookie In response.Cookies
     cookieJar.Add(tempCookie)
Next

Passing post data to the website

Next, I created a StreamWriter class and wrote the post data to it. You can pass any data to the website here in name=value&name=value format.

Dim writer As StreamWriter = New StreamWriter(request.GetRequestStream())
writer.Write("email=username&pass=password")
writer.Close()

Finally…

The following code gets the source code of the webpage returned which is the homepage of your account (i.e home.php), and checks if you are logged in successfully or not.

Dim stream As StreamReader = New StreamReader(response.GetResponseStream())
Dim data As String = stream.ReadToEnd()
response.Close()
 
If data.Contains("<title>Facebook") = True Then
     'LOGGED IN SUCCESSFULLY
End If

I hope this simple example will help you save some time. If you find it useful then do let me know via your comments.

Happy Coding :)