March 1, 2011

tree search algorithm (cont.)

 The previous post is here
============
struct treeNode{
    int element;
    struct treeNode *left;
    struct treeNode *right;
}:
typedef struct treeNode *searchTree;


searchTree makeEmpty(searchTree T){
    if(T!=NULL){
        MakeEmpty(T->left);
        MakeEmpty(T->right);
        free(T);
    }
    return NULL;
}


searchTree findVal(int val, searchTree T){
    if(T==NULL)
        return NULL;
    if(valelement)
        return findVal(val, T->left);
    else if(val>T->element)
        return findVal(val, T->right);
    else
        return T;
}


searchTree findMin(searchTree T){
    if(T!=NULL)
        while(T->left!=NULL)
            T = T->left;
    return T;
}


searchTree insertVal(int val, searchTree T){
    if(T==NULL){
        T=(searchTree)malloc(sizeof(struct treeNode));
        if(T==NULL){
            printf("Error! There is no new memory to allocate.\n");
            exit(0);
        }
        T->element = val;
        T->left = T->right = NULL;
    }
    else{
        if(valelement)
            T->left = insertVal(val, T->left);
        else if(val>T->element)
            T->right = insertVal(val, T->right);
        else
            printf("The element has already in this tree.\n");
    }
    return T;
}


searchTree deleteVal( int val, searchTree T){
    searchTree temp;
    if(T==NULL){
        printf("The element is not found.\n");
        return NULL;
    }
    else if(valelement)
        T->left = deleteVal(val, T->left);
    else if(val>T->element)
        T->right = deleteVal(val, T->right);
    else{        // here, find the specific element
        if(T->left && T->right){
            temp = findMin(T->right);
            T->element = tmp->element;
            T->right = deleteVal(tmp->element, T->right);
        }
        else{
            temp = T;
            if(T->left == NULL)
                T = T->right;
            else if(T->right==NULL)
                T = T->left;
            free(temp);
        }
        return T;
    }
}

// the functions below returns node which element is closest
// and larger in the Tree. We could call it "next"
// assumption1: the inputs are inquiry val and the root node
searchTree nextLarger(int val, searchTree T){
    searchTree temp;
    if(T==NULL){
        printf("There is no tree.\n");
        return NULL;
    }
    if(valelement){
        if(T->left!=NULL){
            temp = T->left;
            while(valelement && temp->left!=NULL){
                T = temp;
                temp = temp->left;
            }
            // This case indicate "temp->left==NULL" causes stop
            // so temp should be the return value
            if(valelement)
                T = temp;
            // otherwise, result might in a new right tree
            // . or the parent node in this layer
            else{
                if (temp->right!=NULL){
                    temp = nextLarger(val, temp->right);
                    if (temp!=NULL)
                        T = temp;
                }
            }
        }
        return T;
    }
    else{
        while(val>=T->element && T->right!=NULL)
            T = T->right;
        if(valelement){
            T = nextLarger(val, T);
            return T;
        }
        else
            return NULL;
    }
}


// assumption2: the input value is a given node in the tree.
// In this case, we might have to trace back.
// As a resutl, the original struct needs a little modification
struct treeNode{
    int element;
    struct treeNode *left;
    struct treeNode *right;
    struct treeNode *parenet;    // to trace back
}:
typedef struct treeNode *searchTree;

searchTree nextLarger2(searchTree start){
    searchTree temp, record;
    if(start==NULL){
        printf("There is not a valid input.\n");
        return NULL;
    }
   
    if(start->right!=NULL){
        start = findMin(start->right);
        return start;
    }
    else if(start->parent!=NULL){
        if(start == start->parent->left)
            return start;
        else{
            while(start->parent!=NULL && start!=start->parent->left)
                start = start->parent;
            if(start==start->parent->left)
                return start;
            else
                return NULL;
        }
    }
}



// references: <Introduction to algorithms>, <Coding Interviews>

// I just did some terrible interviews these days. Yes, some, and terrible.
// So, I wanna record everything here, 

// no matter how stupid and rudimentary it is.
// Also as a means to push myself, everyday a step further.

February 28, 2011

tree search algorithms

// Breadth-First Search
// The tricky part is that we have to know the entire info. about
// the graph, which indicates in the link-matrix graphmatrix

struct node{
    int color;    // 0-white, 1-grey, 2-black
    int index;    // fount order
    int d;         // distance to the root
    struct node *parent;
};
typedef struct node* Node;

void buildBFS1(int *graphmatrix, Node graph, Node start){
    int i=0, n, head, tail;
    Node queue;    // used as stack to do BFS
    Node temp;

    while(graph[i]!=NULL){
        graph[i].color = 0;
        graph[i].index = i;
        graph[i].parent = NULL;
        graph[i].d = 0;
        i++;
    }
    n = i;
    start->color = 1;
    queue = (Node)malloc(n*sizeof(Node));    // not sure here...
    head = tail = 0;
    enqueue(queue, &tail, start);

    while(!isEmpty(head, tail)){
        temp = dequeue(queue, &head);
        for (i=0; i
            if(graphMatrix[temp->index][i]!=0){
                if(graph[i].color==0){
                    graph[i].color = 1;
                    graph[i].d = temp->d+1;
                    graph[i].parent = temp;
                    enqueue(queue, &tail, graph[i]);
                }
            }
        }
        temp->color = 2;
    }
}

void initQueue(int *head, int *tail){
    *head = *tail =0;
}

void enqueue(Node q, int *tail, Node element){
    q[(*tail)++]=element;
}

Node dequeue(Node q, int *head){
    return q[(*head)++];
}

int isEmpty(int head, int tail){
    return head==tail? 1:0;
}

int isFull(int tail, const int size){
    return tail==size? 1:0;
}


// Depth-First Search
// has more knowledge about the structure of the tree
// at the cost of a more complicated struct

struct node{
    int index;
    int color;
    int detected;
    int finished;
    struct node *parent;
}
typedef struct node* Node;

// the original algorithm in the textbook is a little bit wierd
// cause it is different from BFS by no need of starting point
// while it is obvious that starting with different points will
// generate trees with different structures, given the same link-matrix
void buildDFS(int *graphMatrx, Node graph, Node start){
    int i=0, n, time;
    Node temp;
    while(graph[i]!=NULL){
        graph[i].color = 0;
        graph[i].parent = NULL;
        graph[i].detected = graph[i].finished = 0;
        graph[i].index = i;
        i++;
    }
    n = i;
    time = 0;
    graph[1] = temp;
    graph[1] = start;
    start = temp;    // just want to start at the beginning of the array
    while(i>=0){
        if(graph[i].color == 0)
            visitDFS(graphMatrix, graph, i, &time, n);
        i--;
    }
}

void visitDFS(int *graphMatrix, Node graph, int i, int *time, int length){
    graph[i].color = 1;    // grey, begin to visit
    graph[i].detected = ++(*time);
    for (int j=0; j
        if(graphMatrix[graph[i].index][j]!=0){
            if(graph[j].color == 0){
                graph[j].parent = &graph[i];
                visitDFS(graphMatrix, graph, j, time, length);
            }
        }
    }
    graph[i].color = 2;    // black, conclude the visiting
    graph[i].finished = ++(*time);
}


(to be continued)        
=========

reference: <Introduction to algorithms>

February 21, 2011

some abstract

说到Unix为我们所带来的软件开发的哲学,我必需要说一说。Unix遵循的原则是KISS(Keep it simple, stupid)。在http://en.wikipedia.org/wiki/Unix_philosophy 上有很多的基本上大同小异的Unix哲学,都是很经典的。

Doug McIlroy 是认为UNIX的哲学是这样的:三条哲学,简明扼要,就是这三条哲学贯穿着整个Unix世界。尤其是第一条“do one thing and do it well”真是相当精彩!

    * Write programs that do one thing and do it well.
    * Write programs to work together.
    * Write programs to handle text streams, because that is a universal interface.

只要是Unix的程序员,他们会比别的程序员在任何时候都会不停地强调着这三条哲学。

而《The Art of Unix Programming》总结了下面这些哲学,都是至理名言啊。

    * Rule of Modularity: Write simple parts connected by clean interfaces.
    * Rule of Clarity: Clarity is better than cleverness.
    * Rule of Composition: Design programs to be connected to other programs.
    * Rule of Separation: Separate policy from mechanism; separate interfaces from engines.
    * Rule of Simplicity: Design for simplicity; add complexity only where you must.
    * Rule of Parsimony: Write a big program only when it is clear by demonstration that nothing else will do.
    * Rule of Transparency: Design for visibility to make inspection and debugging easier.
    * Rule of Robustness: Robustness is the child of transparency and simplicity.
    * Rule of Representation: Fold knowledge into data so program logic can be stupid and robust.
    * Rule of Least Surprise: In interface design, always do the least surprising thing.
    * Rule of Silence: When a program has nothing surprising to say, it should say nothing.
    * Rule of Repair: When you must fail, fail noisily and as soon as possible.
    * Rule of Economy: Programmer time is expensive; conserve it in preference to machine time.
    * Rule of Generation: Avoid hand-hacking; write programs to write programs when you can.
    * Rule of Optimization: Prototype before polishing. Get it working before you optimize it.
    * Rule of Diversity: Distrust all claims for “one true way”.
    * Rule of Extensibility: Design for the future, because it will be here sooner than you think.

X Windows 的设计者 Mike Gancarz 给出了下面九条哲学思想

   1. Small is beautiful.
   2. Make each program do one thing well.
   3. Build a prototype as soon as possible.
   4. Choose portability over efficiency.
   5. Store data in flat text files.
   6. Use software leverage to your advantage.
   7. Use shell scripts to increase leverage and portability.
   8. Avoid captive user interfaces.
   9. Make every program a filter.


十条不错的编程观点
1) The only “best practice” you should be using all the time is “Use Your Brain”, rather than some so-called "famous" frameworks, methods, classes, or prototypes.
2)Programmers who don’t code in their spare time for fun will never become as good as those that do.
3)Most comments in code are in fact a pernicious form of code duplication, which should explain "why", rather than "how" and "what".
4)XML is highly overrated
5)Not all programmers are created equal
6)”Googling it” is okay!
7)If you only know one language, no matter how well you know it, you’re not a great programmer.
8)Your job is to put yourself out of work. Or, saying, if you can’t be replaced then you can’t be promoted!
9)Design patterns are hurting good design more than they’re helping it.
10)Unit Testing won’t help you write good code

January 8, 2011

job hunting

need to read:
thinking in Java
coding interviews
thinking in C++
CLRS and K&R, again...

in one month?.. ok, i will try.

December 18, 2010

Reply: 这七个月

  
其实我应该好好享受最后一个人过的日子
me: 嗯,其实我也是。

参加不靠谱的活动
me: ok~

读不靠谱的书
me: of course, you can

穿不靠谱的衣服
me: 好吧……

学不靠谱的知识。
me: 没问题~

勾引可爱的小学弟
me: 不行!

然后再勾引学长
me: 不行!!

再勾引单身的男老师
me: 必然不行!!!

或者,只是一个人安静一会儿不去想你。
me: 嗯:)

嗯哼~

c/c++ input/ouput functions

int open(char * filename, int flags)
int open(char * filename, int flags, int mode)

include: fcntl.h
flags = bitwise | or of any of the following:
     O_RDONLY      Only read operations permitted
     O_WRONLY      Only write operations permitted
     O_RDWR        Read and Write operations both permitted
     O_NONBLOCK    Non-blocking, applies to open operation only
     O_APPEND      All writes go to end of file
     O_CREAT       Create file if it doesn't already exist
     O_TRUNC       Delete existing contents of file
     O_EXCL        Open fails if file already exists
     O_SHLOCK      Get a "shared lock" on the file
     O_EXLOCK      Get an "exclusive lock" on the file
     O_DIRECT      Try to avoid all caching of operations
     O_FSYNC       All writes immediately effective, no buffering
     O_NOFOLLOW    If file is symbolic link, open it, don't follow it
mode required if file is created, ignored otherwise.
mode specifies the protection bits, e.g. 0644 = rw-r--r--
returns <0 for error, or integer file descriptor.

int close(int fd)
include: unistd.h
fd = file descriptor as returned by open
returns <0 for error, 0 for success.

int read(int fd, void * ptr, int numbytes)
include: unistd.h
fd = file descriptor as returned by open
ptr = address in memory where data is to be stored;
      may be a pointer of any type.
numbytes = number of bytes to attempt to read
returns <0 for error, 0 for end-of-file,or number of bytes successfully read. (for a non-blocking interactive file, that may be zero).

int write(int fd, void * ptr, int numbytes)
include: unistd.h
fd = file descriptor as returned by open
ptr = address in memory where data already is;
      may be a pointer of any type.
numbytes = number of bytes to attempt to write
returns <=0 for error, or number of bytes successfully written. (for a non-blocking file, that may be less than the number attempted without any errors having occurred).

int lseek(int fd, int position, int startpoint)
include: unistd.h
Sets the file position effective for the next read or write operation.
fd = file descriptor as returned by open
position = position within file: number of bytes between startpoint and the desired position, may be negative.
startpoint = location in file that position is relative to, one of:
     SEEK_SET: Position is number of bytes from beginning of file
     SEEK_END: Position is number of bytes after end of file
     SEEK_CUR: Position is number of bytes after current position
returns <0 for error, or resulting file position relative to beginning of file. Moving beyond the end of the file is permitted; the file is extended in length only if a write occurs beyond the current end of file. Moveing before the beginning of a file is not permitted. A write operation after a move only overwrites the number of bytes actually written.

int stat(char * file, struct stat * info)
include: sys/types.h
include: sys/stat.h
Finds information about a file.
file = The name (or path) for the file.
info = A pointer to an uninitialised stat structure. Even in C++, the type must be "struct stat *" because of the name clash. Information about the file is stored in the info object.
returns <0 for error (including file does not exist), or 0  for success.
The useful fields of a stat object are as follows. All have types that behave like ints, although they may be 16, 32, or 64 bits long.
     st_size: size in bytes
     st_ino: inode number
     st_mode: protection or mode (see below)
     st_nlink: number of hard links
     st_uid: file's owner's identification number
     st_gid: file's group identification number
     st_birthtime: date and time of file creation (see below)
     st_mtime: date and time of last modification (see below)
     st_atime: date and time of last access (see below)
All times are stored as time_t values, as described here. Mode and Protection. st_mode is the logical-or of a number of bits each representing different properties. The named constants for these bits, and their values in octal are:
     S_ISUID  0004000  set user id on execution
     S_IRUSR  0000400  protection: readable by owner
     S_IWUSR  0000200  writable by owner
     S_IXUSR  0000100  executable by owner
     S_IRGRP  0000040  readable by group
     S_IWGRP  0000020  writable by group
     S_IXGRP  0000010  executable by group
     S_IROTH  0000004  readable by all
     S_IWOTH  0000002  writable by all
     S_IXOTH  0000001  executable by all
Four bits of the mode give the file type. The mask for type is S_IFMT = 0170000
if (mode & S_IFMT) is S_IFREG = 0100000,  type = perfectly ordinary file
if (mode & S_IFMT) is S_IFDIR = 0040000,  type = directory
if (mode & S_IFMT) is S_IFLNK = 0120000,  type = symbolic link
if (mode & S_IFMT) is S_IFIFO = 0010000,  type = named pipe
if (mode & S_IFMT) is S_IFSOCK = 0140000,  type = named socket

File Mode or Protection Bits

A file's mode or protection is usually specified visually by 9 characters, for example rw-r--r-- or rwxr-x--x. Each of the letters are (nearly always) 'r' for read permitted, 'w' for write permitted, or 'x' for execute permitted.

The letters always appear in groups of three. Within a group, the order is always 'rwx'. The first group of three indicate operations permitted to the owner of the file; the second group of three indicates operations permitted to other users in the same group as the owner; the third group of three indicates operations permitted to all users who can access the file.

If the file is a directory, 'x' means that files in the directory may be accessed if referred to directly by name, but wildcard substitutions ('*') and ls operations will not be permitted.

Modes are usually represented inside programs by a sequence of three octal digits. each octal digit represents one of the groups of three characters, 4 for 'r' plus 2 for 'w' plus 1 for 'x'. In C and C++ programs remember that numbers with leading zeros are always assumed to be in octal, so the mode 0751 represents rwxr-x--x.

vim setup

The configuration should be done in the file named "vimrc".

For linux os, the directory should be: /etc/vim/vimrc. For Unix, without root privilege, just as I am..., it needs to make a new file named ".vimrc" in the $HOME/ directory. As the vim starting, it will automatically read this file for configuration. And, the punctuation quotes " is the sign for comment.

" syntax highlighting
syntax on
" automatic indentation
set autoindent
" specifically c/c++ indentation
set cindent
" to show the line number for each line
set nu

Have fun:)

Days of our lives

Daisypath Anniversary tickers