Saturday, October 5, 2013

Implement strStr

class Solution {
public:
    char *strStr(char *haystack, char *needle) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int len_h = strlen(haystack);
        int len_n = strlen(needle);
        if (len_h < len_n)
            return NULL;
        if (len_n == 0)
            return haystack;
        
        char *p_h = haystack, *p_n = needle;
        while (p_h <= haystack+len_h-len_n) {
            if (*p_h != *p_n) {
                p_h++;
            }
            else {
                int i;
                for (i = 0; i < len_n; i++) {
                    if (*(p_h+i) != *(p_n+i))
                        break;
                }
                if (i == len_n)
                    return p_h;
                else
                    p_h++;
            }
        }
        return NULL;
    }
};

Tuesday, October 1, 2013

Install numpy and scipy on Mac

Found a useful link about how to install numpy and scipy on mac.

https://github.com/fonnesbeck/ScipySuperpack

Tuesday, September 17, 2013

Image erosion


The image is represented in a two-dimension array. Every pixel of the image can only to assigned to either 0 or 1. If a pixel is 0, just leave it there. If a pixel is 1, we check its four neighbors. If all its four neighbors are 1, leave it there. Otherwise, erode it to 0.
Example:
0 1 1 1 0        0 0 1 0 0
1 1 1 0 0  --> 0 1 0 0 0 
0 1 0 1 1        0 0 0 0 0

Solution:
The difficult part is that every pixel can only be assigned to either 0 or 1. Otherwise, we can assign the 1s which need erosion first to some other value in the first scan. In the second scan, we can change this value to 0.
So here we use to arrays to store the row index and column index for the pixel need erosion.
The problem with this method is that we use to much memory to store the row index and column index. One way to optimize is that we only store the index for two rows. Because the erosion of row 0 will not affect the check for row 2.
bool check (int x, int y, int image[H][M]) {
    if (x>0 && image[x-1][y]==0)
        return true;
    if (x<H-1 && image[x+1][y]==0)
        return true;
    if (y>0 && image[x][y-1]==0)
        return true;
    if (y<W-1 && image[x][y+1]==0)
        return true;
    return false;
}

void erosion_part (vector<int> &row, vector<int> &col, int image[H][M]) {
    for (int i = 0; i < row.size(); i++)
        image[row[i]][col[i]] = 0;
}

void erosion (int image[H][W]) {
    vector<int> row, col;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            if (check(i, j, image)) {
                row.push_back(i);
                col.push_back(j);
            }
        }
    }
    erosion_part (row, col, image);
}

The problem with this method is that we use to much memory to store the row index and column index. One way to optimize is that we only store the index for two rows. Because the erosion of row 0 will not affect the check for row 2.
void erosion_part (vector<int> &row, vector<int> &col, int image[H][M], int end) {
    while (!row.empty()) {
        if (row.front() > end)
            break;
        image[row.front()][col.front()] = 0;
        row.pop_front();
        col.pop_front();
    }
}

void erosion (int image[H][W]) {
    list<int> row, col;
    int start = 0;
    for (int i = 0; i < H; i++) {
        if (i-start >= 2) {
            erosion_part (row, col, image, start);
            row.clear();
            col.clear();
            start++;
        }
        for (int j = 0; j < W; j++) {
            if (check(i, j, image)) {
                row.push_back(i);
                col.push_back(j);
            }
        }
    }
    erosion_part (row, col, H-1);
}

Longest common prefix

Given an array of strings, find the longest common prefix.
Example:
["abc", "a", "ab"] --> "a"
["abcd", "ab", "abc] --> "ab"

Solution:

string lcs (vector<string> array) {
    if (array.empty())
        return "";
    int pos = 0;
    string result = "";
    for (int i = 0; i < array[0].size(); i++) {
        char target = array[0][i];
        for (int j = 1; j < array.size(); j++) {
            if (i >= array[j].size() || array[j][i] != target)
            //a small trick here is that the length of the first string may be longer that some of other 
            //strings in the array. We need to test whether we have reached the end of other strings
                return result;
            else
                result += array[0][i];
        }
    }
    return result;
}

Build a tree from a xml file

Give a xml file like this,
<a>
   <b>Text<\b>
   <c>
      <d>Computer Science<\d>
      <d>Linear Algebra<\d>
   <\c>
   <e> Hello world <\e>
<\a>
Convert the file into a tree
                     <a>
                    /     \       \
                 <b>  <c>   <e>
                          /    \
                       <d>  <d>
Note the result don't have to be a binary tree. To functions are given.
1. getToke(): It returns two values Type and Text. Type includes BEGIN, TEXT, END. Text is the actual content of the token.
2. hasNext(): It will return true until the scan hit the end of the file.

Solution:
You have to first decide how to store the tree structure. Then another problem is how to differentiate between parent and children. We use a stack to store the current parent.

One thing to be careful about is that the xml file may be not in the correct format, i.e. <a>text<\c>. Return NULL in this case.

class Node {
public:
    string name;
    string content;
    vector<Node *> children;
    Node (string n, string c = "");
};

struct Token {
    Type type;
    String content;
};

Node * buildTree (){
    Token t = getToken();
    Node * root = new Node (root.content);
    stack<Node *> s;
    s.push (root);
    
    while (hasNext()) {
        t = getToken();
        if (t.type == BEGIN) {
            Node * tmp = new Node (t.content);
            s.top->children.push_back (tmp);
            s.push (tmp);
            continue;
        }
        if (t.type == TEXT) {
            tmp->content += t.content;
            continue;
        }
        if (t.type == END) {
            //Here you need to check whether the format of xml file is correct
            //If the type of token doesn't match, return NULL
            if (t.content == s.top())
                s.pop();
            else
                return NULL;
        }
    }
    //if the stack is not empty at the end, xml is not correct formatted, return NULL
    if (!s.empty())
        return NULL;
    else
        return root;
}

Tuesday, June 25, 2013

private vs protected vs publis

I'm always confused by the member type in class of c++. There are three types: private, protected and public. In inheritance, there are also there specifiers, private, protected and public. After doing some research on Internet, found two good tutorials for this.

http://www.parashift.com/c++-faq-lite/access-rules.html

http://www.learncpp.com/cpp-tutorial/115-inheritance-and-access-specifiers/

Have fun!

Tuesday, May 7, 2013

Notes for blackjack

To prepare the interviews, I have to delve into 'Crack the Code Interview'. To better understand the OO chapter, I decided to work on a 400-line project, blackjack. I found some good source code online and I'll take notes here.

1. enum
http://www.enel.ucalgary.ca/People/Norman/enel315_winter1997/enum_types/

2. C++ operator overload
http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html

3. Polymorphism: Virtual member function, abstract function
http://www.cplusplus.com/doc/tutorial/polymorphism/

4. protected specifier
http://msdn.microsoft.com/en-us/library/e761de5s(v=vs.71).aspx

5. Can we pass a derived class if the function is expecting the base class as argument?

If you have a function void foo(base b) and pass my_derived to it, that derived is converted to base, loosing any information that was not in base. You can't recover that information in any way.

If you have void foo(base* b) and pass &my_derived to it, no conversion occurs. foo only thinks that it is working with a base. You still can't use members of derived though. foo must be written in such way that it works with base itself or its other children that don't have that member. It is possible, however, to check that b is in fact pointing to a derived object and cast it to derived* using dynamic_cast or some virtual function.


6. Slicing

If You have a base class A and a derived class B, then You can do the following.
void wantAnA(A myA)
{
   // work with myA
}

B derived;
// work with the object "derived"
wantAnA(derived);
Now the method wantAnA needs a copy of derived. However, the object derivedcannot be copied completely, as the class B could invent additional member variables which are not in its base class A.
Therefore, to call wantAnA, the compiler will "slice off" all additional members of the derived class. The result might be an object you did not want to create, because
  • it may be incomplete,
  • it behaves like an A-object (all special behaviour of the class B is lost).
7. const issues
When doing the coding, I noticed a scenario like this.

void aClass::foo const () {
      vector<T>::iterator iter; //This is wrong since it's within a const function
      vector<T>::const_iterator iter; //This works fine
}

7.1 The const for foo means that within the function, the value of the class members will not be changed. 
class aClass {
private:
     int a;
     int *b;
};

aClass::foo const {
     a = 5; //Wrong
    int x = a; //OK
    *b = 100; //OK, it's changing the variable pointed to by b, not b itself
    b = &x; //Wrong
}

To fully understand this, it's necessary to notice the difference between const pointer and pointer to const variables. Here is a good demo about this.

Back to the iterator, const_iterator acts like a pointer to const variable and iterator acts like a normal pointer. I didn't delve into the reason, just remember for a const function, if you need to use an iterator, const_iterator is always safer than iterator.