Showing posts with label dsa. Show all posts
Showing posts with label dsa. Show all posts

Tuesday, February 8, 2011

exercise code

refer to your year1 structure programming book

1. pg 121 . create a new function that calculates the difference of 2 numbers

2a. pg 146. modify the code to use a vector instead of an array.
2.b. pass by reference the vector to a new function to add 5 into each elements of the vector. Cout the vector in the main() to verify the value.

Tuesday, January 25, 2011

[DSA] binary tree

terminology
the root: the beginning of a tree.

every node is possibly the root node for the nodes below it. eg. the parent node.

parent node, the n-1 lvl of the n's lvl node.
child node, the n+1 lvl of the n's lvl node.

(n-1)
|
___n____
| |
(n+1) (n+1)

edge, the path for traversal to happend.
leaves, the lowest lvl in the tree.

a binary tree, a tree where each parent node only have 2 children.

binary search tree (BST)

a binary tree, where the root node is always the middle value of the list of values.

remember binary search from previous week?
what are the 2 possible condition to be satisfied before one can qualify for binary search?

BST it self is not efficient. there is a possibility that the insertion of the node will cause it to behave like a worst case binary tree.

we need a sorted BST, where each time a node is inserted the tree is "sorted" to find out which is the new node. What are the implications if the tree are always sorted when insertion or deletion is done??? Is there any other possible way to enhance it?

3 ways for tree traversal
-Inorder
Traverse the left subtree
Visit the current parent
Traverse the right subtree

-Preorder
Visit the current parent
Traverse the left subtree
Traverse the right subtree

-Postorder
Traverse the left subtree
Traverse the right subtree
Visit the current parent


uses of binary tree data structure
- compression
- encoding
- conversion of mathematical formula to prefix or post fix form
- data structure of choice for "fast" retrieval of search items

there are many other type of binary tree
full binary tree
perfect binary tree
balanced binary tree
self balancing binary tree

Monday, January 24, 2011

[DSA] map and set container



map<string,int> mapp;
map<string,int>::iterator mit;
string name_search;

    mapp.insert(map<string,int>::value_type("Amy",81377442));
    mapp.insert(map<string,int>::value_type("Bob",32731631));
    mapp.insert(map<string,int>::value_type("Catherine",32387163));
    mapp.insert(map<string,int>::value_type("Danny",21321312));
    mapp.insert(map<string,int>::value_type("Ecuador",54543947));
    mapp.insert(map<string,int>::value_type("Felicia",32535612));
    mapp.insert(map<string,int>::value_type("Genie",24172312));



refer to above on how the map data structure is used.


use the map data structure to satisfy the following requirements.
1. create a phone book application that can store name and phone number.
1a. perform a display all entry in the phone book.
2. phone number need to that ensure it is 8 numerical digits only.
3. initialize the phone book application with some data.
4. perform a lookup for a random entry in the phone book and display it.

challenge
5. Suggest a method to store address, email and msn address to the phone book that you have already created.
6. what are the advantages and disadvantages of your method??? explain why you choose the design.

Tuesday, January 18, 2011

[DSA] searching


Have you ever tried to find something in your house/room. Yet can't seems to ever find it. Now, lets not talk about misplacing items out of carelessness. Let's discuss how to "find" items in your wardrobe.

Assume you have your apparels hanging in the wardrobe, how would you "find" your favorite shirt/dress? would you start looking from the left hand side? the right hand side or simply in the middle???

If you find 1 apparel at a time from either direction, that is linear search. The worst case scenario is, you would traverse all your apparels before finding your favourite.

If you have sorted your apparels according to a certain sequence, eg, warm colours to the right and cold colours to the left, you can simply start finding from the middle, then to the left if your favourite falls in the cold colour. This is binary search. searching time can be reduced significantly.

Again, if you do like what i did, simply pile up all my apparels in the wardrobe without sorting/folding/ironing it. "Finding" for a particular item in the wardrobe can be disastrous.


Linear Search => O(N)
Go through the entire array of items to lookup on the searched key. The sequence of items are not sorted.
Best case , the 1st item in the array.
Worst case, the last item in the array.
Average case, traverse for half of the array

Binary Search => O(logN)
Uses a divide and conquer method.
array of items must be sorted first, involves a cost.
L <> root
|---|---|
L---M---R


For any array of 1000000 items, Linear search need 500000 comparison (assume an average case), Binary Search 20 comparison.

Pop Quiz
1. Create a generic code of linear search to take in different data type.
2. Create a Binary Search tht uses recursive method.
3. Use find() or search() from the STL to do a lookup of a string, among many strings stored in the memory

Monday, January 17, 2011

[DSA] Sorting


Here comes the interesting part in algorithms.
Sorting and searching are the crowns in the algorithm topic. So to speak, these are hottt topics for research in computer science world.

Efficiency, cost. Remember???

We will be examining bubble sort, insertion sort, selection sort and merge sort in details. Studying the complexity of the above algorithms, and not forgetting the implementation of the algorithm. Both DIY code and STL.

But Why Bother to Sort?



Here comes the question>>>>>>>>>

1. Implement sort descending for Bubble Sort, Selection Sort, Insertion Sort, STL sort. Use int arrays or vectors to try it out.

2. In our session, we use integer to demonstrate sorting. Is it possible to sort characters, strings, double, objects etc? Use vector or arrays to try it out.

3. Use the sorting algorithm of your choice, sort 10 tropical fruits of your choice.

4. On top of the previous implementation, create a class for fruits with 2 parameter namely int price and string fruitName. Sort the 10 tropical fruits according to fruit name or price. Your implementation should be able to sort both price and fruitName ASC or DESC. A menu might help in here.

5. Lastly, what considerations when we need to ponder when comparing 2 arbitrary Sort Algo A and Sort Algo B. How would we really know that A is better then B ?

There might be more then one implementation of the above sorting algorithm. Below are my flavor for the 3 algorithm. Codes are commented for easy following.
//bubble sort

//insertion sort

//selection sort

//merge sort


Tuesday, January 11, 2011

[DSA] Queue

Long time ago when i was still working in shenton way...
I need to wear shirt+neck tie+business slack. If there is a need to meet then client, add another blazer under the blazing sun. It rhythms rite~

Geek like me, I find matching colour of my outfits seem to take forever to learn. There is no hard and fast rule. Best, it is very subjective. Different people will give you different preference and a piece of their mind. ARGHzzzzz. How nice if (day=monday){setBlue();} can be applied to matching my attire.

So to play safe, I bought seven sets of outfit that the colour would match generally. Hang them in my wardrobe from left to right for monday to sunday (I work 8 days per week). I applied FIFO (first in first out) on my "queue" of attire. hehe. Because, I always take from my LHS (Left Hand Side) every morning for my business, and replenish at the RHS after it is done from the laundry.

To hide the fact that i am lazy to choose my attire, and there is a high probability I would wear the same thing for that day of the week for all the weeks in a year. I did a one left shift on my "Queue". Then my wardrobe queue would behave like a barrel shift register that shifts by one bit. Hence my algorithm would keep me safe from the optic blasts of the "fashion police". Sad to say, I still did not escape the scrutiny of the fashionista.

There is this girl in my office, which takes a mental note on the pattern of the occurrence of my attire. She observed my algorithm for about 3 weeks then I am busted.... No, she did not became my wife.

Drill Questions
1. Create a queue of 10 items, of your choice.
2. Assume that the 4th item in the queue is of higher priority, retrieve it first.
3. display the remaining items in the queue.

HEROES ONLY!
4. Create a queue of objects. Each object have a different priority 1-10. 1 is highest priority, 10 otherwise. Object with the highest priority in the Queue need to be service first.

5. Based on 4, create objects at random interval of 1s to 10s and enqueue them. You can assume that the queue is dequeue at every 1 second

6. In the emergency ward, some cases are more serious then the other. Assume there is more then 1 queue is available. Suggest a method that would give Queue tickets to non-priority case, while ensuring life threatening case get service accordingly.

Monday, January 10, 2011

[DSA] stack

Stack, a last in first out (LIFO) type of data structure.
very similar to our STL list learned last week, there is also a STL stack.

|a|
|b|
|c|

Long long long time ago when i was still a student and still staying in the hall (Now I am still a student, constantly learning new things!). My friends always asked me why i always wear the same t-shirt from monday to sunday. Being the computer science student, I try to explain to them the reason using the stack data structure. Every time my laundry is done, it is folded nicely (assume please) into a stack. When I fold my t-shirt, and placed them in a stack. I fold them in the same order for every week and always take from the top of the stack of tshirts so that my wardrobe will not be messy(assume it is not messy).

Talking about needing randomization in folding t-shirt and putting them on a stack. Every morning wake up, I am always in a rush. So, I always choose the first t-shirt (the top in stack data structure) of the stack. The cycle repeats it self again and again. Sometimes, I do accidentally pull a tshirt out of the middle of the stack and the stack of tshirt just collapsed. Things got better when I found another person to fold my laundry when I was staying in hall!

Stack is efficient, minimal disturbance to the memory when data is inserted/deleted because only the top of the stack is modified. But when the 5th element of a 10element in a stack need to be retrieve, there is a lot of manual code needed for manipulation. Hence the efficiency and performance of the stack data structure is not satisfied.

So......what to do with the stack data structure? It can be used to store the dungeon level information. How many of you have played the game dungeons and dragons?? The assumption is that player can only go to 1 level above or 1 level below the current level of dungeon. Hence, using a stack to store is more sensible. Of course, a list can be used too. But... what are the consequences????

Have you wondered how the mouse in the micro-mouse competition know how to escape from the maze??? All movements of the mouse, eg forward, backward, left, right are stored onto the stack. When a dead end is encountered, the mouse will take a step back by simply pop off the top item on the stack. This is for navigation that requires a step back look left/right algorithm.

Other uses of stack, is in the operating system, where the system variable is stored. The stack is used to hold temporary variable of an executing program. Another stack is used to store the starting address of programs. What happens when the stack used to store variable is "overflow" ????


Drill question for the week,
1. Create a stack of 10 items.
2. retrieve the 5th item on the stack.
3. display the remaining item on the stack.

4. Modify week 4's decimal to binary conversion program and implement with stack.
4. Modify week 5's palindrome checking program and implement with stack.

Monday, January 3, 2011

[DSA] Linked List

Linked List (LL)

Let assume today is your first day in school and your are appointed as the class rep. Most likely the first task you and need to do is to write down the names and contact information of your class mates.

But how are you going to do it??? Do you randomly scribble the information on some paper napkins and shoved it into your bag? Or write down the names and contact information one by one, in a list form? Or fired up your web browser and point to docs.google.com and start making a spreadsheet? 

The data you have entered is unsorted, so this tiny piece of paper/document serves as your lookup table when you need to retrieve some information. E.g your classmate's phone number
This week, we are going to explore the several api calls to use STL list to insert data, manipulate data and to retrieve data.

Say you want to find out your new classmate catherine for her phone number. How would you look for the information in the list? Most of us would look from top to bottom, some bottom to up, some start in the middle and traverse up or down. Inherently, you still lookup the information from the list one by one. All this methods to find her name doesn't really matter, because the list of information is unsorted, it will still take n+1 effort . The effort to lookup a name in the list gets bigger when the list grow longer and longer.

In the list of names you have,how would you input new names for student that just got into your class? Do you add it at the end of the list? Or simply insert the name to any position where the space permits?

All the above is the analogy for the Linked List used in the computer

Items that is stored in Linked List have to be travsersed sequentially. There are no random access iterators to access link list. Hence, you need to declare an iterator of the same data type that is used by the STL list container.

When you are designing the code and you needed data to be access randomly, Linked list is not the best option. Traversing the whole list of items takes time. The time required will grow accordingly to the size of the list. So, vectors or arrays are the best option (at the moment of learning). The items in vectors and arrays are placed side by side in memory world and can be access in a random fashion.

Items of a Linked List are not required to be placed side by side in the memory of the computer. How items are "linked" in a link list are done by the maintaiannce of the "header" pointer and the "tail" pointer. Pointers, as we have learned in the previous sessions, are variables that store the memory address of the items we are interested with. The tail pointer of the current items contains the address of the next item, ie. the value stored in the head poiter.

0->hP|DATA1|tP->hP|DATA2|tP->hP|DATA3|tP->0


Changing the values of the pointer variable requires only O(1) effort. Hence, the linked list is efficient when data/items are required to be inserted randomly in the list.

If the deletion of an item is required in the linked list. All need to be done is to modify the tail pointer of the current item, skipping the item we want to delete and points to the head pointer of the item next to the deleted item. In other words, we are merely copying the address in the tail pointer of the deleted item to the previous item's tail pointer. cool huh. No more holes left in the memory, no more statically declared memory that is left unsed, no more ugly algorithm to compact the array after a deletion of items.

All the above, are naked to the untrained eye. Users can't see the differences, only the programmer does.

DRill Questions:
1. create a list to store name of your classmates.
2. print out class list
3. "find" a particular person in the list. return found or not found.
4. Find out a method to attach the gpa score to the names in the list above.
hint: use class and OOP.
5. sort the list by gpa descending.
hint, try out stl algorithm

Tuesday, November 23, 2010

[DSA] General Maths Algo

Long long long time ago.....
Programs are written in C++ to solve mathematical problem, not much of user click here and there on the GUI. Mathematical problem can range from calculating relative distance, trajectory etc.

To make life simple, there was "math.h" in C(include math in c++) to help make the calculation. "math.h" alone might not be sufficient to cover each and every possible scenario, hence some programmer do have their custom class to do the math related to their program.

We have studied general maths routine such as converting from decimal to binary (d2b) and at least 2 method to calculate Greatest Common Divisor(GCD). Through the d2b function, we learned how to decompose the "steps" to get the binary from the decimal and translate the "steps" it into code.

The direct application of the GCD I could thought of is the computation of the public key and private key pairs in the RSA algorithm (http://en.wikipedia.org/wiki/RSA). Encryption is as simple as calling a function (java and C++ have the library), but behind the function call, these are the necessary code to calculate the key pairs.

Notice there are 2 possible way of programming the GCD, through the recursive method or the iterative method which we have discussed previously. Is it easier to understand the recursive code then the iterative code???




Below are the questions for the week.
IP address in the form of A.B.C.D, where each octet A,B,C,D range from 0 to 255 in decimal.
1. How many bits each octet hold?
2. What are the "steps" required to convert one octet to binary?
3. Write the function that would convert the IP and gives it equivalence in binary.


note: you could modify from the d2b function, or propose a simpler algorithm based on the characteristic of the IP address's octet

Monday, November 22, 2010

[DSA] Iteration and recursion

Look into the mirror and observe your self. Look into your eyes, you will notice that in your pupil (the dark/blue/green color portion of the eye if you are asian/Caucasian) you can see yourself in it. Now, look into that pupil on the mirror. You will observe yourself again, albeit a scaled version. That is what i call recursion, you will see yourself again and again in your pupil.

Assume that you can see even the smallest detail of yourself through the mirror, notice that there is no end to the vision?

This is not good for recursion in computer science/programming. The program keeps executing recursively, until the system resources run out. So, at least a condition for the recursion to stop must be defined, which what we called the base case.

Anything that is solved iteratively, can be solved recursively.

Fibonacci The first number of the sequence is 0, the second number is 1, and each subsequent number is equal to the sum of the previous two numbers of the sequence itself. Once the formula is established, it is easy to figure out the code.
Fibonacci is a natural candidate for recursion, because it need to use data that are computed before in that particular series. Hence, we need to store this temporary data somewhere. In recursion, temporary data is stored on the stack. 

Drill Questions
1. Write a iteration fuction that calculates 2^n. 2 to the power of n. n being the input from cin.
2. Write a recursive function that calculates 2^n. n being the input from cin.
3. when n is very large, what are the parameters need to take into considerations?
4. What do you observed for the 1. and 2. when n is very large?
5. Is 2^n a natural candidate for recursion??

Monday, November 15, 2010

[DSA] STL

My favorite quote from Issac Newton "I am Standing on the shoulders of giants" greatly illustrate the idea of STL. Code have been written by other programmers, using the template feature to greatly help other programmers to overcome programming difficulties. I.e, reduce the time from concept to code.


Being a lazy programmer I am (yes I do admit I like to find the easiest and shortest possible way of writing a piece of code), I do not like to reinvent the wheel.

As in write my own custom code that serves the same purpose as those already written/tested/proven best code by the c++ community.

Why make your life suffer when there are already ready code for you to use?

Programming, in general, is the ability to synthesize code to solve real-world problem by making use of available code. Only in the very dire situation (think high security, high accuracy and the need for real time operation), custom code is needed. *read=> proprietary software*
By learning all the basic building blocks of programming such as template, variable passing etc. When one day this dire state occur, YOU have the ability to create the code library to save the day~!

The STL contains three main components:


Containers
Iterators
Algorithms


Containers, as the name suggested is some form of storage for our data.

Iterators, instead of the programmer manually keeping track on 
ALL pointers declared and used (not an easy feat when the code is in the range of >10k lines ), this STL-Iterator helps the programmer to achieve the same objective.

Algorithms, fancy writing some code to solve the question in the math tutorial? Here is the partial solution. You need to piece this building blocks together.


Drill question



1. We have written some code to check whether a given word is a palindrome in the previous week, by using some member functions of the string class. Good work guys. 
Now, use STL containers, iterators to achieve the same objective.

2. Write a phonebook directory that let the user to store
1. first name
2. phone number

(Store some dummy data into the phone book for testing,)
and the ability to "scroll" the phone book

and the ability to "search" for a particular entry in the phone book.

hint: use ready code from
-Containers
-Iterators
-Algorithms

*non-OOP implementation is acceptable for now.*


http://www.cppreference.com/wiki/stl/algorithm/start
http://www.cplusplus.com/reference/stl/

Tuesday, November 9, 2010

[DSA] string class

I hope you have enjoyed and learned some "know how" of writing a program from scratch, with our lil' palindrome example.

To make our lives easier, C++ have lots of library for us to choose from
#include < string > is one of them. Take note string and cstring. both are different!

If you check out the book pg260. There is a piece of code that is very similar of what we have done today. It is using CString instead of String.


Drill Question


Write a name generator (star wars name anybody? hehe) software.
1. The software takes in a name for input and
2. think of the "magic" algorithm to generate a "NINJA" name. Or any name modifiers you can think of. Similar to those name generators you have played on facebook. I guess pretty much of everybody have generated at least once.  Code it FREE STYLE ~maybe you want to start by storing 10 sample first name and 10 sample last name. Which gives a 10 to 10 mapping. Easily 100 names~

Append part of your original name to the sample name "randomly".
3. Check out the string member functions attached~

below are the member functions of String. http://www.cplusplus.com/reference/string/string/

Member functions

(constructor) Construct string object (constructor member)
operator= String assignment (public member function)


Iterators:
begin Return iterator to beginning (public member function)
end Return iterator to end (public member function)
rbegin Return reverse iterator to reverse beginning (public member function)
rend Return reverse iterator to reverse end (public member function)


Capacity:
size Return length of string (public member function)
length Return length of string (public member function)
max_size Return maximum size of string (public member function)
resize Resize string (public member function)
capacity Return size of allocated storage (public member function)
reserve Request a change in capacity (public member function)
clear Clear string (public member function)
empty Test if string is empty (public member function)


Element access:
operator[] Get character in string (public member function)
at Get character in string (public member function)


Modifiers:
operator+= Append to string (public member function)
append Append to string (public member function)
push_back Append character to string (public member function)
assign Assign content to string (public member function)
insert Insert into string (public member function)
erase Erase characters from string (public member function)
replace Replace part of string (public member function)
copy Copy sequence of characters from string (public member function)
swap Swap contents with another string (public member function)


String operations:
c_str Get C string equivalent (public member function)
data Get string data (public member function)
get_allocator Get allocator (public member function)
find Find content in string (public member function)
rfind Find last occurrence of content in string (public member function)
find_first_of Find character in string (public member function)
find_last_of Find character in string from the end (public member function)
find_first_not_of Find absence of character in string
find_last_not_of Find absence of character in string from the end (public member function)
substr Generate substring (public member function)
compare Compare strings (public member function)

Monday, November 8, 2010

[DSA] template class

Template, as the name suggested is a standard or generic way/form we could use for creating different output. For an example, you would ask for a report template from your senior so that you more or less know how what is expected from you.

One of the benefits of programming through a template, it reduces the effort to recode the same function/class but pass in a different variable type. Our good friend the STL Algorithms is the best example of programming template. Imagine the sort() function need to be rewrite again and again and again for each type of variable...............

I strongly do not advocate of getting report from other people and change it to your name. That is not template nor referencing. It is called plagiarism.

A function template or class template, beside used with primary variable, eg int, char, double. It can be used with data structures too. As usual, it is possible to pass in more then 1 parameter of the same or different variable type to the function template or class template.

reference the code below. NOTE: The Code is NOT COMPLETE you need to fix it before you could use it.

Q1. What does both of the function trying to do??? Is there a way to generalize it without repeating the "same" code?
Q2. Populate the given code with a template function that will double each number stored as elements in the data structure. Is it possible to double a char or a string stored in the data structure??

//===CHALLENGE==> HEROES ONLY=====//
Q3. Write a template function reverselist() that could take in a list display the content of the list and store the contents of the list on to a stack and later display the content of the stack.
Q4. Is there a more efficient way to create a test for a palindrome????



Tuesday, November 2, 2010

[DSA] File Op

Data need to be saved somewhere. The reason being, if all data are stored in memory and the computer get accidentally turned off. The effect would be epidemic!
Data output using fstream are clear text by default! ENCRYPT any sensitive info before output to file!!!!!

Some text file are delimited in a certain way, for example below.
sample of comma delimited file=> aa,bb,cc
sample of semicol delimited file=>aa;bb;cc

File operations of the program, should be able to read in the lines, and "parse" the input accordingly and stored into the required variable.

This usually happens when legacy software needed an upgrade to the most-IN technology (Programmer Guru Mantra= If it ain't spoil, don't fix it). However, the data are not compatible. One common feature of software, it has the ability to "dump" data out of the system.

As as programmer, we need to write code to extract those that required to the new system. Therefore, we still get to keep our jobs, make ourself valuable.

Regarding on the issue of Out Sourcing to other country. Fret Not. Why would the company would entrust their data to a 3rd party other then their employer? The audit trail of hands dipped into the data would be clearer and easier to trace. Hence the accountability.

With Great monies, comes great responsibilities.

Talking about file IO and security, take a look at the game below.
http://www.takegame.com/logical/htm/boxworld.htm

I played the game when i was still a teenager like most of you. My friend challenged me to complete the game (eg Lvl 99) in the shortest possible time. Few of us, being kiasu (hokkien colloquial for afraid to loose), keep comparing each other's progress. Me, for being me went to my usual corner and gave my friend Lvl99 at the end of the day. Guess how I manage to get it done????

Homework
The sample of file operations are in the writescore.cpp and readscore.cpp. Compile and run it to get a feel of how File I/O is done.

Drill Questions
1. Write a program that READS IN records (eg A.txt) that are semicol delimited eg
tom 19 dcpe/2B/01 DSA B+;kelly 18 dcpe/2B/01 DSA A; .....

2. Write a program that WRITE OUT records (eg B.txt) that are semicol delimited eg
tom 19 dcpe/2B/01 DSA B+; kelly 18 dcpe/2B/01 DSA A; ....

3. write a program that reads in Q1 but modifies to comma delimited and output to a new file.

HINT: It is good to have a menu driven system to choose between the options instead of running 2 cpp projects concurrently.

Monday, November 1, 2010

[DSA] Class & Objects

In programming, class is a common topic. No matter is C++ or Java, the same concept on class still applies. Killing N birds with 1 stone.

In programming, objects are end product of a class. Objects represent data that are generalized by the class.

Think of the Class as a cookie cutter, Objects are the cookies, the dough is generic material that all cookie need to use. Each object may have some unique attribute(s), such you would sprinkle some chocolate on the dough to make a chocolate chip cookie or add some almond to it almond cookie. In the generalization point of view (the class pov), it is still cookie. All cookie uses the same dough.



Think about it, I went to eat dim sum http://en.wikipedia.org/wiki/Dim_sum last weekend and realize some of the items taste the same. I wonder they use the class method to make it. I.e generic minced meat to make dim sum of different shapes.

How would data be generalized and yet representable?
For an example, Cats and dogs. Both are mammals. Both have four legs. Does it means that the cat is a dog and vice versa???!!! Sure we can think of some other attribute that differentiates a dog and a cat. dog barks and cat meows.

So we can have a class named pets, we can have data attribute of pet type, pet breed etc. Below is the sample code for inventory I have for the dog class for my imaginary dog kennel.




drill question 1, create a class for a cat shelter? Think of the attribute you can put into the class to represent the data of a cat. Some attributes like owner telephone and address should be set as private, and accompany by the neccesary get and set function.

drill question 2, create bank account objects with classes as specified in DS03 Objects Q3.


Notice from the code I posted, I have to manually track the objects, manually remember what objects I have created and use it.
In programming, the ability to link one topic learned previously to another topic, "mesh" the knowledge together is very important. So to speak.
From data structures , we know that it is convenient to manipulate data in a data structure, and depends on the condition we can choose the best data structure to represent the data. Can we "link" class&objects with data structures?

Refer to the code below,






Drill question 3. Based on the class you have created, can you store the objects in a data structure of your choice???? Think of what are the possible applications for data structures "meshing" with class&objects?
HINT: try to use constructors



below is the code for the SpStudent class in the slides, with my comments






Monday, October 25, 2010

[DSA] pointers stuff

Well done to those that have completed the drill question (well, at least you did the “EASY” one) last week. To those that did my STUN question, KUDOS!!!! By doing this exercise, you have examine the buggy code and correctly identified the syntax errors, logic erros and some went further of discovering the differences of using “cin” and “getline”. The application and synthesis skills, such as isolating the buggy portion of the code, using the debugger, and reading error message from the IDE are particularly important especially in programming. These are the skills that I hope you can exhibit or demonstrate at the future assessments to come.

For those that have yet to attempt, please give it a try. And for those have done, try out the “HERO” question. Everybody loves to be a hero and get "worshiped" (I assumed that is).

Pointer is used for example when sorting a data structure. It is “expensive” to move the data physically, hence, changing the value of the pointer that points to the data is considered “cheaper”.

Below is a chunk of code that demonstrates pointers, the differences when pointers are applied to “char array” and “int array”. YOU are MOST WELCOMED to add more examples of using a pointer in c++.





Pointers come a long history in C and C++, some hate it so much but some really love it. Take it like a durian. Pointers enable the manipulation of the memory directly. PLEASE be EXTRA meticulous when it comes to programming pointers. Commented code really helps a lot for others to look, learn, debug another programmer’s code.

Now Comes the drill question for pointer. Write a program that calculates the volume of a cube (A x A x A), which need to satisfy some "requirement" identified from the "problem analysis" (which is done by me for you)
1. Read in 2 inputs from the user
2. Code a function that takes in this 2 parameter passed by reference and the result is stored in another variable, which is also accessible by the pointer ptrArea. Print out the area for the user.
3. Code another function, which takes in the ptrArea and calculate the volume of the cube.


Now come to the drill question array. Arrays are “containers” that can be used to store data in a structural manner. There are some disadvantages when it comes to using array. First, memory need to be allocated first (static). What happends when there are many copies of the same programme are running? Since memory is allocated, and used up but there are more data to come, array do not have the flexibility to increase like the vector. What are the other cons of using array compare to any other data structure?

Consider using “arrays”. Code a simple 100 seat cinema booking system that will do the following
1. Given (x,y) coordinate set the seat to be occupied.
2. Suggest a scheme/algorithm that detects duplicate seat entry.

Sunday, October 17, 2010

[DSA] Common Mistakes in Programming

There are few categories of mistakes/error/bug in programming. Suchs as logic erros, syntax errors, core dumpz (run time error)/
I came across many many types of mistakes in programming that student commit. These mitakes fall majorly into the syntax error which is the easiest to troubleshoot. As compared to logic errors, there are formal mathematical way to prove that the logic and the premise it holds.

As the old programming guru’s mantra: “It takes more pairs of eyes to spot the bug”

Below is NAF (Need A Fix) buggy code that I have created (50lines only....easy). Your "TASK" is to "SOLVE IT", "FIX IT", PLS DO NOT EAT IT!!!

PLS POST/SHARE your answers here, add in as comments.
//=======================================================




//=========================================================

NO KICK???????????!!!!!!!!!!!

try the below (100lines, 5qns), covers strings, STL containers, iterators. Errors such as syntax error, runtime error and a little bit of logic error.

Note: "HEROES ONLY"

//==========================================================



Tuesday, August 31, 2010

[DSA] feedback~~!

RAWWRRRRRRRRRR is Feeding time....ooops feedback time.
feedback about me, you can use the below as a guide

1. my teaching
2. your learning
3. what you have learned from me
4. what you want me to improve on

I hope to see you guys again, prolly FYP or other modules.
It was fun and fulfilling to see you all keep upgrading your code to impress, yours truly.