搜尋此網誌

2011年7月31日 星期日

賽德克巴萊(Seediq Bale)曾經被改成大陸拍的!!!

請看下列Link:
威尼斯演展官網

並比較下圖

電腦數字系統轉換







我是台灣人!!

目前住在台灣這片土地上的人,不能否認身上或多或少有帶著中國的​傳統和悠久歷史文化的血液,但也不能否認,你現在住的這塊土地是​台灣,不是中國!!!更不是中華民國.就像美國人的祖先大部分是​從英國來的,美國人也不會說自己是英國人,這就是所謂的落地生根​, 我文化上認同我所知所學的傳統中國文化,可是我在政治立場上,一​定要堅持我是台灣人,不是中國人,這兩點要分開來看,不能混為一​談.現在就是太多人搞不清楚這之間的分別,才一直誤以為自己是中​國人!!

2011年7月30日 星期六

BBS鄉民小劇場短片收集

現在鄉民小劇場太熱門了,不免俗的也來收集這些小劇場,一次可以看全部.















2011年7月29日 星期五

ACM-3n+1 Problem

It is a Java solution.
You should focus on the green part and fix input part for your use.


package acm;

import java.io.*;
import java.util.*;

public class ThreeNPlusOne {
public static void main(String[] args) throws IOException {
ArrayList<String> userInput = new ArrayList<String>();
int intCases = 0;
System.out.println("How many test cases to run?");
BufferedReader bs = new BufferedReader(new InputStreamReader(System.in));
String cases = bs.readLine();
intCases = Integer.parseInt(cases);
while (intCases != userInput.size()) {
System.out
.println("Please enter 2 numbers m and n,separate them by dot.");
userInput.add(bs.readLine());
}
Iterator it = userInput.iterator();
while (it.hasNext()) {
String numbers = (String) (it.next());
int[] ns = getInts(numbers);
int first = ns[0];
int second = ns[1];
System.out.println(first + " " + second + " "+ threeN(first, second));
}

}

public static int threeN(int a, int b) {
int max= 0;
for (int i = a; i <= b; ) {
int tmp=i;
int count = 0;
while (true) {
count++;
if (i == 1) {
break;
} else {
if (i % 2 != 0) {
i = 3 * i + 1;
} else {
i /= 2;
}
}
}
if (count > max) {
max = count;
}
i=++tmp;
}
return max;
}

public static int[] getInts(String str) {
int totalNumbers = str.split(",").length;
int[] ints = new int[totalNumbers];
for (int i = 0; i < totalNumbers; i++) {
ints[i] = Integer.parseInt(str.split(",")[i].trim());
}
return ints;
}

}

CPU 規格解釋

Processor Number:用來區別同一公司的不同產品的編號.

#cores:有多少個核心在一顆cpu上.

#threads:一個核心有一個process,一個process有一個thread.

clock speed:時脈,也就是頻率.
i.e:
2 MHz (2 million cycles/second):每秒執行2百萬次運算.
3 GHz (3 billion cycles/second):每秒執行30億次運算.
cpu執行的速度越快,價格當然越高.

L2 cache:cpu每次會從ram,也就是記憶體裡面拿資料出來做運算,但因為cpu速度太快了,因此處理器製造商,便在cpu和記憶體之間加了諸如L1, L2的cache(快取記憶體)來當作橋樑,也就是
cpu-L2 cache(Store data)-physical memory

FSB Speed: Front side bus又稱為north bridge or 北橋, 負責處理cpu和記憶體的溝通,
通常L2 cache包含在FSB裡面.速度當然是越快越好.

Lithography:製程. 每個製成會使用到不同的化學方法或物理方法來製造這各chip,數字越小代表需要越先進的技術來開發,想當然爾會越貴

Max TDP(Thermal design power):cpu運算會產生熱,這個數字代表冷卻系統需要耗費多少瓦特的電力來散熱,所以越快的cpu比起低階的cpu,會更快產生更多的熱,因此也就耗電.

部落格經營記事--當月瀏覽人次首度超過100

賀,我的部落格這個月竟然瀏覽人次超過100哩,超乎我預期,之前有一搭沒一搭的寫,所以來逛的人也

是稀稀疏疏的,因此我下定決心每天至少要發2~3篇文章才可以,我把部落格當成小花圃一般來照料,

果然有付出,月底就看到收穫了.很高興,要再接再厲的發文才行.

2011年7月28日 星期四

ACM-light, more light problem

According to the "Mathematical Induction", we found out that when the serial are 1,4,9,16 ...the final bulb is on ,which means that number has a square root . On the other hand, besides those numbers, the bulb is off. Therefore , following is my Java solution:

ACM-Greatest Common Denominator

It is a Java based solution. The operation is dividing the two numbers mutually until one of them equals zero. The green part is the main mechanism .


package acm;

import java.io.*;
import java.util.*;

public class GCD {
public static void main(String[] args) throws IOException {
ArrayList<String> userInput = new ArrayList<String>();
while (true) {
int intCases = 0;
System.out.println("How many test cases to run?(from 1 to 1000)?");
BufferedReader bs = new BufferedReader(new InputStreamReader(
System.in));
String cases = bs.readLine();
intCases = Integer.parseInt(cases);
if (intCases < 1 || intCases > 1000) {
System.out.println("Please enter a valid number!!");
} else {
System.out.println("Please enter 2 numbers m and n,separate them by dot.");
System.out.println("ex: 12,60");
while (intCases != userInput.size()) {
userInput.add(bs.readLine());
}
break;
}
}
Iterator it=userInput.iterator();
while(it.hasNext()){
String numbers=(String)(it.next());
int[] ns=getInts(numbers);
System.out.println(gcd(ns[0],ns[1]));
}

}

public static int gcd(int a, int b) {
while (a != 0 && b != 0) {
if (a > b)
a %= b;
else
b %= a;
}
if (a == 0)
return b;
else
return a;
}


public static int[] getInts(String str){
int totalNumbers=str.split(",").length;
int[] ints=new int[totalNumbers];
for(int i=0;i<totalNumbers;i++){
ints[i]=Integer.parseInt(str.split(",")[i]);
}
return ints;
}

}

2011年7月27日 星期三

數學相關單字的英翻中

radical sign:根號
exponential equation:指數方程式.
quadratic :二次方程式.
asymptotes:漸進線
instantaneous:瞬間
substitution:代換
conjugate : 共軛的
slope: 斜率
quotient:商,除的意思
tangent: 切線
secant:割線
steeper:陡峭的
workbook練習本
power:次方
hypotenuse:斜邊
adjacent:鄰邊
products:乘積
concavity: 凹度
time span:時間寬度
rectangle:矩形
Integration: Backwards Differentiation
QUADRATIC:二次
denominator:分母
perpendicular:垂直
composition:構成,成分,組成
symmetry:對稱
vertex: 頂點
polynomial: 多項式
sketch:畫輪廓
conic:錐
parabola :拋物線
intercept:截取
ellipses:橢圓

2011年7月25日 星期一

OpenMP-shared for loop



#include <omp.h>
#include <iostream>
using namespace std;
int main() {
int n=10;
#pragma omp parallel shared(n)
{
#pragma omp for
for (int i=0; i<n; i++)
cout <<"Thread "<<omp_get_thread_num()<<" executes loop iteration "<< i<<endl;
}
return 0;
}



references:
OpenMP Official Web sites
Using OpenMP: Portable Shared Memory Parallel Programming

OpenMP-Parallel Constructor

Parallel constructor(平行結構):可以告訴compile,以下的程式碼要用parallel 的方式執行,
並且程式設計師也可以運用此結構,來個別定義thread的行為.
i.e.

#include <omp.h>
#include <iostream>
using namespace std;
int main() {
#pragma omp parallel
{
cout <<"The parallel region is executed by thread "<<omp_get_thread_num();
if (omp_get_thread_num() == 1) {
cout <<" Thread "<<omp_get_thread_num()<<" does things differently\n";
}
}
return 0;
}


附帶一提parallel region有兩種狀態:active以及inactive.
所謂的active是指有多個thread在執行運算,若只有一個thread在做運算的話就是inactive的狀態.


references:
OpenMP Official Web sites
Using OpenMP: Portable Shared Memory Parallel Programming

OpenMP conditional compilation

Conditional compilation is used to prevent unwanted results created from a non openmp compliant compiler .

Following is its format:

#ifdef _OPENMP
#include <omp.h>
#else
#define omp_get_thread_num() 0
#endif
//some code here
int TID = omp_get_thread_num();


references:
OpenMP Official Web sites
Using OpenMP: Portable Shared Memory Parallel Programming

2011年7月23日 星期六

面板股

面板雙虎當中,有一隻融資餘額太高,可是另一隻是正常水位,可以逢低進一點點,畢竟還沒有真的賺錢,買太多也不適很明智,單純只是融資餘額清的差不多到可以進場的價位.

好聽的日文歌曲介紹

1.真夏の果実 (PV) SOUTHERN ALL STARS:這首歌張學友有翻唱過,好聽喔



2.貓的報恩主題曲-梁靜茹翻唱為小手拉大手



3.很愛很愛你原曲 KIRORO-長い間



4.ホワイトベリー - 夏祭り / Whiteberry-->放煙火的時候可以聽



5.ボーイフレンド aiko (歌:ラズベリー) --aiko boyfriend



6.B'z 今夜月の見える丘に (木村拓哉主演的日劇主題曲)



7.Do As Infinity / 深い森



8.hitomi - LOVE 2000

9.I WISH - Asu e No Tobira 明日への扉 --另一歌版本為---旅立ちの日に



10.Time goes by/ELT



11.Dragon Ash - Life goes on



12.花×花 あ~よかった



13.Da Pump - if



14.PV Hysteric Blue - 春~spring

15. それが大事

2011年7月22日 星期五

Circular Queue Array



#include <iostream>
#define capacity 5
using namespace std;

class ArrayQueue {
public:
int size;
int myFrontPos, myBackPos;
int array[capacity];
ArrayQueue(){
size=0;
myFrontPos=0;
myBackPos=0;
}

void enqueue(int number) {
int newBack=(myBackPos+1)%capacity;
if (size==capacity) {
cout<<"queue is full!!"<<endl;
} else {
array[myBackPos]=number;
myBackPos=newBack;
size++;
}
}

void dequeue() {
if (size==0) {
cout<<"queue is empty!!"<<endl;
} else {
myFrontPos=(myFrontPos+1)%capacity;
size--;;
}

}

void display() {
for(int i=0;i<size;i++){
cout <<array[i]<<endl;
}

}

};

int main() {
ArrayQueue aq;
aq.enqueue(1);
aq.enqueue(2);
aq.enqueue(3);
aq.enqueue(4);
aq.enqueue(5);
aq.dequeue();
aq.enqueue(6);
aq.display();
return 0;
}

2011年7月21日 星期四

C++ array (陣列)

C++有兩種陣列:靜態(Static)和動態(Dynamic)陣列.在c++ array的使用上要注意的地方是無論靜態或動態陣列,都必須要固定一個常數變數當作array的size;以下先列出靜態陣列的例子:

const int n=100;是用來指定陣列的size;然後第一個for loop是塞值進入陣列,第二個for迴圈是把目前的陣列值印出來.


沒有塞值進入陣列的話,印出來的陣列值是殘存在那個記憶體位置裡的值,如下列例子:




我們也可用pointer(指標)的方式來對陣列存取,
陣列的第一個元素的位址(address)就是陣列的名稱,
因此我們可以把此名稱指定給poiner然後循序遞增或遞減pointer來存取陣列,
如下範例:



int* ptr =a;:把此名稱指定給poiner
ptr++;:循序遞增或遞減pointer來存取陣列

Subsequently, let's introduce the Dynamic Array.
The differences between static and dynamic are the declaration and memory handling.
For declaration, a "new" reserved word needs to be along with the variable.And we also need to delete the pointer variable to release the reserved memory block. It is a very important thing to prevent from a memory leak.
Following is the example code, you can focus on the colored words.


OpenMP Introduction(OpenMP 介紹)

1.OpenMP
  • 採取 fork-join(?分叉-結合?)的方式來做平行運算.

  • 因為對於c/c++/fortan語言的擴充性, openmp可以用來發展平行化的應用程式(Parallel Application Development)

  • It is a programming interface

  • shared-memory parallel programs
  • 2011年7月20日 星期三

    OpenMp 環境配置 for eclipse

    我是使用eclipse for c++ developer,一開始一直會出現1各undefined GOMP_parallel_end 的錯誤後來我發現只要到專案的property裡去設定就解決了.以下是圖檔,因為每個版本的eclipse不盡相同,請各位根據圖找到對應的欄位去改
    要改的兩個項目是GCC c++ compiler 還有MingGW c++ linker



    OpenMP-HelloWorld

    open mp是可以把程式平行化執行的c/c++ library.open mp很常被用在遊戲的動畫處理方面.另一方面因為現在的電腦都是雙核心的cpu,如果應用程式沒有寫成平行化的方式,無法完全發揮雙核心cpu的威力,不免俗的我的第一個open mp 程式當然是c++版本的hello world.網路上很多例子都是用c的方式來呈現,因為我不熟悉c,所以小改成c++的方式來實作.若compile顯示ignore #pragma的警告訊息, 那麼要在complie command line加上"-fopenmp"參數


    #include <omp.h>
    #include <iostream>
    using namespace std;
    int main() {
    #pragma omp parallel
    cout<<"Hello from thread "<<omp_get_thread_num()<<", nthreads"
    << omp_get_num_threads()<<endl;
    return 0;
    }



    #pragma omp parallel:是openmp的directives(指示字?),會產生threads來執行,此段程式碼.
    omp_get_thread_num():此函式用來回傳thread編號
    omp_get_num_threads():用來回傳thread總數



    如果只需要一個thread執行程式的話可以用#pragma omp single


    #include <omp.h>
    #include <iostream>
    using namespace std;
    int main() {
    #pragma omp single
    cout<<"Hello from thread "<<omp_get_thread_num()<<", nthreads"
    << omp_get_num_threads()<<endl;
    return 0;
    }

    2011-07-20-大盤加權指數看法

    前一陣子很不好做,多空雙巴,做短單真的不適合.
    目前上檔反壓在8820點左右,下檔支撐在8000~8200這個區間.
    最好的走法還是慢慢整理,然後慢慢向高點邁進.

    2011年7月19日 星期二

    Binary Search Tree C++

    Java程式開發和維護

    以下是Binary Search Tree的實作,綠色字的部分是用preOrder遞迴的方式列出這棵樹所有的元素.所謂的 preOrder的意思是說先找root,然後找Left node, then Right node.另外還有,inOrder 和postOrder,分別把root放在中間找亦或是把root最後找
    
    
    

    Java binary search

    BST with Java 行程安排應用程式

    2011年7月18日 星期一

    Queue Implemented by a Linked List

    Queue:是一種先進先出的資料結構(First In First Out).
    下面的範例程式使用C++ 的Linked List來實現Queue.




    #include <iostream>
    using namespace std;

    class Node {

    public:
    int data;
    Node* nxtNode;
    Node(int _data) {
    data=_data;//Data
    nxtNode=NULL;//pointer to next one
    }
    };

    class LinkedList {
    Node* previous;
    Node* next;
    public:
    LinkedList() {
    previous=NULL;
    next=NULL;
    }

    void insert(Node * _node) {
    if (previous==NULL) {
    previous= next= _node;//first node
    } else {
    (*next).nxtNode=_node;
    next=_node;
    }
    }

    void displayAll() {
    Node* tmp=previous;
    while(tmp!=NULL){
    cout<<(*tmp).data <<endl;
    tmp=(*tmp).nxtNode;
    }
    }
    };

    int main() {
    Node* firstNode=new Node(1);
    Node* secondNode=new Node(2);
    Node* thirdNode=new Node(3);
    LinkedList ll;
    ll.insert(firstNode);
    ll.insert(secondNode);
    ll.insert(thirdNode);
    ll.displayAll();
    return 0;
    }

    Stack implementation linked list

    以下所有的資料結構都是用C++實作,
      linked list
    • 用指標(pointer)實作的list可以無限制的擴充大小,但無法像陣列一樣可以直接(Direct)或是隨機存取(Random Access)儲存的資料.

    • 基本的linkeded list(鏈結串列),包含一個data的欄位,和一個next pointer欄位用來指向下一個資料


    以下是以一個LinkedList實作Stack(First In Last Out)的例子

    2011年7月17日 星期日

    C++ Const的用法

  • const int* ptr :固定value,但可改變address

  • int* const ptr :固定address,但可改變value
  • 2011年7月16日 星期六

    C++ Reference Variables Usage(C++參考變數的使用)

    可以把參考變數(Reference Variable)想像成一個變數的別名或替代名稱.而且此變數和原來的變數存在於共同的記憶體位置,並且擁有相同的值.

    #include <iostream>
    using namespace std;

    int main() {
    int a=1;
    int & a1=a;//a1 is a reference variable
    cout << a1 <<endl;
    return 0;
    }



    之前有提過c++和Java的基本型別變數(int ,double等)都是call by value的
    call by reference or value若是想要call by reference,在c++可以用reference帶替pointer(指標)當作傳入函式的參數.如下例:

    #include <iostream>
    using namespace std;
    void sum4(int &);

    int main() {
    int a=1;
    sum4(a);
    cout << a <<endl;
    return 0;
    }

    void sum4(int & a) {
    a=2;
    }



    在這個例子中,雖然並沒有建立一個reference變數,但當基本變數a傳入此function sum4()的時候,會自動被當成reference變數來對待,也就是call by reference,因此在函式內改變a的值之後,
    原本變數a的值也會一起被改變.

  • Reference變數也可以當作函式的回傳值.


  • #include <iostream>
    using namespace std;
    int & sum5(int &);

    int main() {
    int a=1;
    sum5(a)=3;
    cout << a << endl;
    return 0;
    }

    int & sum5(int &a){
    return a;
    }



    因為sum5回傳的是(reference),也就是記憶體位置,因此改變a的值為3,也會同時改變原本的變數值.若在sum5的前方加上關鍵字const,那麼我們便不能直接使用sum5所return回來的reference來改變變數值,如下例子:

    #include <iostream>
    using namespace std;
    const int & sum5(int &);

    int main() {
    int a=1;
    sum5(a)=3;
    cout << a << endl;
    return 0;
    }

    const int & sum5(int &a){
    return a;
    }

    "那些年,我們一起追的女孩,觀後感"

    C++ 變數的生存範圍和種類

    C++的變數範圍(Scope)有三種

    • 區域變數(Local Variables):在函式內宣告的變數,當跳離或函式結束執行的時候,此變數的記憶體空間會自動被回收

    • 靜態變數(Static Variables):在程式主體和函式之間的變數.程式結束執行的時候記憶體會自動被作業系統回收

    • 動態變數(Dynamic Variables):實際執行時期用到的變數.要用delete手動把存在記憶體的變數值刪掉,或是程式結束執行的時候會被作業系統自動回收.



    #include <iostream>
    using namespace std;

    void sum3(int);
    int main() {
    int a=1;//Static Variable
    sum3(a);
    int * ptr=new int;//Dynamic Variable
    *ptr=2;
    cout << "before delete: "<<endl;
    cout << *ptr<<endl;
    delete ptr;
    cout << "after delete:" <<endl;
    cout << *ptr<<endl;
    return 0;
    }

    void sum3(int a) {
    int b=a;//Local Variable
    cout << b<<"\n";
    }

    C++ Namespace(命名空間)用法

    c++的namespace和Java的package有異曲同工之妙,也就是說宣告在不同namespace的function.即便擁有同樣的名字也不會衝突到,可獨立使用.
    以下是範例程式:
    #include <iostream>
    using namespace std;

    namespace MyException {
    class Exception {
    public:
    void mesg() {
    cout << "Exception Occurred !!"<<endl;
    }
    };
    }


    void sum2(int, int) throw (MyException::Exception);
    int main() {
    int a=1;
    int b=1;
    try {
    sum2(a, b);
    } catch (MyException::Exception & ex) {// start of exception handler
    ex.mesg();
    }
    return 0;
    }

    void sum2(int a, int b) throw (MyException::Exception) {
    if (a==b) {
    throw MyException::Exception();
    }
    cout << a+b<<"\n";
    }




    解說:
    先命名一個namespace為MyException的block,然後在block內定義一個Exception類別,接下來使用"命名空間::類別名稱"來使用此類別


    也可以使用兩個namespace的方式來更進一步減少name collision,不過在使用的時候要記得存取每一層namespace的名字,compile才有辦法正確找到要使用的類別.


    namespace MyException {
    namespace SecondLevel {
    class Exception {
    public:
    void mesg() {
    cout << "Exception Occurred !!"<<endl;
    }
    };
    }
    }

    2011年7月15日 星期五

    C++ 例外處理(Exception Handler)

    當函式(Function),throw(丟)出例外的時候,要用一個try..catch的block把這個問題處理掉或顯示出來給使用者知道.範例程式如下:紅色字的部分是exception的運用,
    #include <iostream>
    using namespace std;
    void sum(int, int);

    int main() {
    int a=1;
    int b=1;

    try {
    sum(a, b);
    } catch (const char * s) {// start of exception handler
    cout << s <<endl;
    }

    return 0;
    }
    void sum(int a, int b) {
    if (a==b) {

    throw "This Combination is unacceptable!!";

    }
    cout << a+b<<"\n";
    }






    紅色字的部分是表示當function sum(int,int)在try block拋出string的錯誤訊息時,catch block(區塊)要把此錯誤訊息印出來.


    Exception class(例外類別)



    前一個範例是拋出字串,這一個範例是拋出例外類別.使用這一個方法的好處是我們可以為exception分類出不同類別,以方便辨識.另外一方面,也提升了重用性(re-usability).


    #include <iostream>
    using namespace std;

    class Exception {
    public:
    void mesg() {
    cout << "Exception Occurred !!"<<endl;
    }
    };
    void sum1(int, int) throw (Exception);

    int main() {
    int a=1;
    int b=1;
    try {
    sum1(a, b);
    } catch (Exception & ex) {// start of exception handler
    ex.mesg();
    }

    return 0;
    }

    void sum1(int a, int b) throw (Exception) {
    if (a==b) {
    throw Exception();
    }
    cout << a+b<<"\n";
    }



    解說:
    第一部分是宣告一個Exception class(例外類別)
    第二部分部分只是把拋出字串,改為拋出此例外類別.
    第三部分部分是函式的實做.要記得在定義define(定義)以及declaration(宣告)的時候加上throw關鍵字指定要丟出何種類外類別.

    宏達電也不適合買進

    宏達電從高點跌下來後,融資餘額屢創新高,這不是好現象
    況且電子產品的價格,以及利潤會隨著競爭者的加入
    和產品的普及化而降低,所以最賺錢的時候已漸漸遠離
    用這麼高的價錢來看待這檔股票,似乎要審慎考慮一番.

    C++ Function Templates (函式模板)

    如果寫了一個function ,ex:兩個整數相加


    void sum(int , int);


    這樣寫的話可以將整數相加,若是同樣的用法要將兩個double(也就是浮點數)相加的時候,還要再寫一個版本給浮點數使用,這種情況可以運用function template來解決


    先宣告function template: 大寫 T可代表任意型態的變數


    template <class T> void sum(T , T);


    在程式碼實作的部分


    void sum(T a, T b) {
    cout << a+b;
    }


    下列是完整的程式:


    #include <iostream>
    using namespace std;
    template <class T> void sum(T, T);

    int main() {
    int a=1, b=2;
    double c=1.1, d=2.2;
    sum(a, b) ;
    sum(c, d) ;
    return 0;
    }
    template <class T> void sum(T a, T b) {
    cout << a+b<<"\n";
    }


    接下來要介紹(Overloaded Templates)多載化的模板


    如果sum()這個函式的名字不變,但傳入的參數改為三個,
    那麼這種情形便稱作多載,多載化的版本也是要先宣告template,然後在實做出來.
    請注意紅色字的部分是新增出來的多載化的程式碼.





    #include <iostream>
    using namespace std;
    template <class T> void sum(T, T);
    template <class T> void sum(T, T, T);

    int main() {
    int a=1, b=2;
    double c=1.1, d=2.2 ,e=3.3;
    sum(a, b) ;//3
    sum(c, d) ;//3.3
    sum(c, d, e)//6.6 ;
    return 0;
    }
    template <class T> void sum(T a, T b) {
    cout << a+b<<"\n";
    }

    template <class T> void sum(T a, T b, T c){
    cout << a+b+c<<"\n";
    }



    2011年7月14日 星期四

    演算法分析(Algorithm Analysis)


    如何判別一個程式寫得好不好,可以用這個程式需要花費的記憶體,或是說要花多少時間才能解出答案,來判斷.因為現在硬體的價格很大眾化.所以我們可以專注在,時間上的討論. 有一個叫做Big-O的概念: 因為會影響時間的因素很多,因此這個概念主要是以討論程式執行的次數多寡來決定要花多少時間.一般我們都是採取比較嚴格的標準檢視程式,所以主要都是討論,在最差的情形下,這程式要花多少時間找出答案.


    比如說

    for (int i=0; i<n; i++) {

    }


    假如答案在最後一項,迴圈要跑到n-1,也就是最後一個才找到答案,我們用O(n),來表示這個迴圈要花線性時間來找出答案.
    又如


    answer=n*2;


    因為答案只需要一次就找出來了,我們用O(1)來表示程式只需要常數時間就會找到答案
    又若我們可以把數字排序後再來找答案,那麼所需要的時間只有一半而已.
    假設1,2,3,4,用Binary Search只需要1~2次即可找出答案,所以可以用O(logN)
    來表示只要對數的時間即可找出答案. 我們可以這麼去想, 4=2^2 ,以2為基底的log: log4=2;
    所以把線性時間乘以2為基底的log,即為log N.

    2011年7月11日 星期一

    軼代和遞迴Iterative and Recursive

    遞迴的整體概念是把同樣類似重複的工作,分拆到最小的單位來做,然後慢慢把小單位的結果集合成大單位的結果,然後成為答案.
    遞迴要有兩個要素:1.基本元素,也可說是終止條件 2.遞迴判斷條件,
    例如:2^0 =1; 2^1=2*2^0; 2^2=2*2^1, 2^3=2*2^2,到最後我們可以歸納為
    x^0=1,這個就是基本條件, 又若n>0的話, x^n=x*x^n-1;這個就是遞迴條件.
    以下是以n的幾次方分別用用遞迴和軼代的方式來實作的程式碼:


    #include <iostream>
    using namespace std;

    int recursive(int, int);

    int main() {
    cout << recursive(2,3);
    return 0;

    }

    int recursive(int x, int n){
    if(n==0){
    return 1;
    }else{
    return x*recursive(x, n-1);
    }
    }






    所有的遞迴和Iterative都可以互換,跑出同樣的結果,把上列程式用Iterative來寫變成:


    #include <iostream>
    using namespace std;

    int recursive(int, int);

    int main() {
    cout << recursive(2, 3);
    return 0;

    }

    int recursive(int x, int n) {
    int answer=1;
    if (n==0) {
    return answer;
    } else {
    for (int i=0; i<n; i++) {
    answer *=x;
    }
    }
    return answer;
    }




    但遞迴較佔記憶體空間.

    divide and conquer with recursive


    遞迴常被使用在分割-處理的使用上,很多二分(Binary)相關的演算法都是用recursive實作

    c++ Typedef的用法


    typedef可以用來為常用的變數型態設定方便自己識別的名稱.



    #include <iostream>
    using namespace std;

    typedef int Integer;

    int main() {
    Integer a=1;
    Integer * number= &a;
    Integer * number2= number;
    (*number2)=3;
    cout << *(number) << "\n";
    return 0;
    }


    C++指標(Pointer)介紹


    1. 指標可以用來指定一個記憶體位址儲存變數資料,用"&"符號可以取出變數的記憶體位址,"*"符號則是取出實際所儲存的值



    #include <iostream>
    using namespace std;

    int main() {
    int a=1;
    int * number= &a;
    cout << *(number) << "\n";
    return 0;
    }





    2. 指標也可以互相指定到同一個記憶體位址,但要很小心,萬一任何一個指標更動到實際所儲存值,那麼另一個也會受影響到



    #include <iostream>
    using namespace std;

    int main() {
    int a=1;
    int * number= &a;
    int * number2= number;
    (*number2)=3;
    cout << *(number) << "\n";
    return 0;
    }

    2011年7月9日 星期六

    Constructor in C++

    為類別建立constructor(建構子)是一個好習慣,建構子是用來初始化實體物件的狀態,http://www.blogger.com/img/blank.gif
    若是使用者沒有自己定義的constructor,系統預設會建立一個空白的建構子給每一個物件.



    你或許也會有興趣的主題:
    c++繼承

    Inheritance C++ : C++ 繼承範例

    C++ 和Java在繼承方面很不一樣,C++允許多重繼承,但Java不允許
    Following, I will start to describe how to write a inherited class in C++
    以下列出C++繼承的寫法

    2011年7月8日 星期五

    運用C++的指標(Pointer)來做動態記憶體(Dynamic Memory Allocation)配置






    在執行時期對於未知的輸入值,要採用動態記憶體的方式,來處理變數,也就是用指標來指向
    某個記憶體位置來儲存變數.
    若在compile時期已知道變數值的話,用靜態的方式宣告和儲存變數即可.
    在下列的例子,因為我們不知道,使用者會輸入甚麼值,所以用動態記憶體的方式來做.
    當程式結束前,一定要記得把記憶體用delete釋放掉,才不會導致日後有memory overflow的風險.


    Linear Search in C++(C++實作線性搜尋)

    使用Recursion來實作C++快速排序法(Quick Sort)




    其他排序法Other sort algorithm.
    Selection Sort

    Selection Sort in C++

    來過請留下痕跡,無論是留言,給建議或是點閱有興趣的廣告
    都是支持繼續寫網誌的動力.



    The complexity of selection sort is O(n^2)
    selection sort(選擇排序)的基本概念是,找出最大或最小的數字,放在最左邊,然後再從剩下的數字中,找出最大或最小的值,依次由左到右放,直到所有的數字都檢查過為止.





    other sort algorithms:
    Quick Sort

    2011年7月7日 星期四

    C++和Java的傳值和傳址(pass by reference in java and c++)



    Java和C++對於陣列型態變數的存取都是直接在記憶體上做(call by reference),所以會改變變數值,同樣的對於

    基本型態如int,皆為複製一份拷貝來做,並不會影響到原來的值,(call by value)

    Java sample:



    C++ sample:



    對於傳入函式的使用者自訂物件,Java也是call by value,但在c++很特別的地方是,除非programmer指定要傳入的是address,若傳入的是value,是會被函式內的區域變數(Local Variable)覆蓋掉,無法使用,看下例便知:

    台股股王x達x落難

    其實有反彈的話都要趕快賣掉,
    因為M頭都出現了,加上融資餘額
    有攀高的跡象,代表著大戶丟出來的籌碼
    都被散戶接走了,這對於個股來說不是好現象.

    Binary Search C++

    使用Binary Search的前提是一個sorted的陣列.