2015年11月29日 星期日

RSA加密法 & C 程式實作 & openssl 產生key

一、簡介:
  RSA是一種非對稱加密方式,使用者利用公鑰加密,或是使用私鑰解密。使用的數字通常很大(目前為1024 bit以上)。

二、流程:
  1. 產生鑰匙:
    A. 取兩質數p和q,並另N = p * q
    B. 設定 r 為(p - 1) * (q - 1)的公倍數。如:r = (p - 1) * (q - 1)
    C. 找一個e與r互質(且小於r)
    D. 找出e在mod r下的乘法反元素d  (e * d mod r = 1)
    E. (e, N)為公鑰;(d, N)則為私鑰

  2. 加密:
    密文 = (明文)e mod N
  3. 解密:
    明文 = (密文)d mod N

三、實作:
  1. 產生鑰匙: 利用openssl可以產生鑰匙
   
$openssl genrsa -out <file>.pem <key bit>

   
$openssl rsa -text -in <file>.pem
(轉為可讀的形式)
產生的key:
modulus即為N
publicExponent即為e
Private-Key即為d
也就是,使用(publicExponent, modulus)加密;使用(Private-Key, modulus)解密
最下面RSA private key為decode前的樣子(pem格式)

  2. 程式碼完全參照參考網址:(除了)
http://www.codedata.com.tw/social-coding/rsa-c-implementation/
(除了power有改變)

#include <stdio.h>
#include <assert.h>
#include <stdint.h>


#define BigInt uint64_t


BigInt newBigInt(char *str) {
  return atoi(str);
}

char tempStr[1025];

char *big2str(BigInt a) {
  sprintf(tempStr, "%lld", a);
  return tempStr;
}


BigInt mul(BigInt a, BigInt b) {
  return a*b;
}


BigInt div(BigInt a, BigInt b) {
  return a/b;
}


BigInt mod(BigInt a, BigInt n) {
  return a%n;
}



BigInt inv(BigInt e, BigInt r) {
  BigInt d;
  for (d=2; d<r; d++) {
    BigInt ed = mul(e, d); // re = (e*d) % r;
    BigInt re = mod(ed,r);
    if (re == 1) {
      printf("e=%lld d=%lld r=%lld (e*d) mod r=%lld\n", e, d, r, re);
      return d;
    }
  }
  assert(0);
}




BigInt Encrypt::power(BigInt a, BigInt k, BigInt N) {
    BigInt l_out = 1;



    while (k != 0)
    {



        if (k & 0x01)
        {
            l_out *= a;

            l_out = mod(l_out, N);
        }
        a *= a;
        a = mod(a, N);
        k = k >> 1;
    }
    return l_out;
}



int main() {
  BigInt p = newBigInt("2213"), q = newBigInt("2663");
  BigInt N = mul(p, q);
  BigInt r = mul(p-1, q-1);
  printf("N=%s r=%s\n", big2str(N), big2str(r));
  BigInt e = newBigInt("4723");
  BigInt d = inv(e, r);
  BigInt m = newBigInt("3320");
  printf("m=%s\n", big2str(m));
  BigInt c = power(m, e, N);
  printf("c=%s\n", big2str(c));
  BigInt m2 = power(c, d, N);
  printf("m2=%s\n", big2str(m2));
}


ref:
http://www.codedata.com.tw/social-coding/rsa-c-implementation/


2015年8月26日 星期三

Profiling tool: gprof (分析程式執行的時間)

gprof 是一個可以分析程式個function使用多少次的工具
(包含執行次數、消耗時間等等)

。使用方式:

1. 在用gcc compile時,加上-pg選項:

$ gcc  -pg test.c -o test_gprof

2. 執行程式:

$ ./test_gprof

執行後會發現產生一個gmon.out檔

3. 利用gprof 打開gmon.out和原本的執行檔:

$ gprof test_gprof gmon.out

。結果:



Ref:
http://www.thegeekstuff.com/2012/08/gprof-tutorial/

2015年7月10日 星期五

vi/vim筆記

模式:

  指令模式:
  輸入模式: 在指令模式按i或a進入輸入模式;按Esc離開輸入模式

指令:

 <模式切換>

  i: 進入輸入模式(文字在指標前)
  a: 進入輸入模式(文字在指標後)
  [Esc]: 離開輸入模式

 <指標移動>

  $: 移到行末
  0: 移到行首
  :[num]: 跳到第num行
  %: 跳到對應的括號
  gg: 跳到檔案底一列
  G: 跳到檔案最後一列
  [num][Enter]: 往下跳num行

<修改>

  u: 復原
  [Ctrl]+r: 重作指令
  d [num]: 刪除num行
  dd: 刪除一行
  y [num]: 複製num行
  yy: 複製一行
  p: 從緩衝貼上(刪除或複製的均會存在緩衝)
       (剪下可用刪除+貼上達成)
  v: 字串標記
  V: 行標記

<搜尋與取代>

  /[str]: 往下找出str字串
  ?[str]: 往上找出str字串
  n: 往下搜尋相同字串
  N: 往上搜尋相同字串
  *: 找出指標所在的字串
  :[範圍]s/[比對字串]/[取代字串]/[g,c,i]: 將比對字串取代為取代字串。gic為控制選項。g表示整行全部;c表示取代前確認;i表示不分大小寫
   e.g.
    :%s/abc/def/  :把abc換成def
  :nohlsearch: 暫時關掉highlight
  :noh: 暫時關掉highlight

<存檔>

  :w: 存檔
  :q: 關閉vi

<行首插入>

游標移動到要插入的地方
[Ctrl]+v: 標記行(區塊)
I: 插入文字
[Esc]: 結束插入,標記的行(區塊)會插入文字

e.g.:在行首插入";"
按下[Ctrl]+v標記行

按下I並插入文字

按下Esc,完成插入。

<行尾插入>

  同行首插入,但利用A進入輸入模式,而不是用原本的I

<視窗>

  :new [filename]: 在新視窗開啟filename
  :only: 只保留當前視窗,其餘關閉
  [Ctrl]+w 切換視窗;再按箭頭下切換到下方視窗,再按箭頭上切換到上方視窗。
  :q 同樣也用q關閉視窗

<分頁>

  :tabe [filename]: 在新分頁中開啟檔案
  :tabN: 切換上一個分頁
  :tabn: 切換下一個分頁
  :tabclose: 關掉分頁
  :tabonly: 只保留當前分頁
  另外,在開啟vim時可以將多個檔案開在不同視窗:(利用-p)
  e.g.:
   vim -p <file1> <file2>

<排版>

  =: 自動排版
  e.g.
    ggVG=
    (檔案首行,列模式,檔案底行,自動排版)
  e.g.
    =[num]
    排版num行
Ref:
http://www2.nsysu.edu.tw/csmlab/unix/vi_command.htm
http://awei791129.pixnet.net/blog/post/29353976-%5Blinux%5D%5Bvi%5D-vi-or-vim-%E7%9A%84%E6%90%9C%E5%B0%8B%E5%8F%96%E4%BB%A3%E5%8A%9F%E8%83%BD
http://www.vixual.net/blog/archives/234

2015年7月8日 星期三

Image processing:seam carving

一、簡介:

Seam carving是content-based的image resiz時,也就是在image放大縮小時,對不重要的部份進行調整,影像重要的部份則不更改。如此,影像較重要的部份較不會有變形的問題。

二、方法:

1. 影像縮小:

  1-1. 找出每個pixel的energy。

  1-2. 找出圖片的seam
利用類似DP

  1-3. 刪除seam

2. 影像放大:

  2-1. 利用和影響縮小一樣的方式找出多條seam

  2-2. 對於每一條seam複製一次,並和周圍平均,插入在原seam右邊(左右放大)或下面(上下放大)

3. 左右及上下同時ressize:

  應該找一個順序,輪流移除col和row。順序取決於energy大小。
  這時候應該計算移除col和移除row比較energy大小,選擇移除後較小的。
  可參考原文:


三、延伸

1. specify object:

  由於有些情況背景太過複雜,有可能導致計算seams時,會通過重要的物體,因此讓使用者
點出物體,並將物體的energy調為最大,如此在計算Seams時便不會經過物體

  1-1. 讓使用者點出物體

  1-2. 讓在物體內部的pixel energy調整為最大

  1-3. 紀錄energy,之後更改(如放大縮小)以這個energy map為主

2. object remove:

  讓使用者點出物體,將所有在物體內部的pixel把energy調到最小,再利用多次的影像縮小即可以移除物體。若要讓影像恢復原本大小,再做影像放大,調整回原大小即可。
  2-1. 讓使用者點出物體

  2-2. 讓在物體內部的pixel energy調整為最小
    這裡是計算整張圖片最大的energy再做負數當作最小值。

  2-3. 移除等於物體寬度(或高度)的seams

3. content amplify:

  利用多次的縮小再放大,可以把比較不重要的東西消除,達到內容加強的效果。


Ref:
 wiki: https://en.wikipedia.org/wiki/Seam_carving
https://compvisionlab.wordpress.com/2013/03/24/seam-carving-matlab/
http://kirilllykov.github.io/blog/2013/06/06/seam-carving-algorithm/

2015年6月20日 星期六

jquery-Slider


Ref: https://jqueryui.com/slider/#range
包含多個jquery套件
可以參考內容去更改
以下只以range slider作為範例

1. 在html中加入link:
<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"></link>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
2. 在html裡加一個id=slider-range的div
<div id="slider-range"></div>

3. 在script裡initial bar:
$(function() {
    $("#slider-range").slider({
      range: true,
      min: 0,
      max: 500,
      values: [ 75, 300 ],
      slide: function( event, ui ) {
        // do somethong when value change
        // ui.values[0]: left value
        // ui.values[1]: right value
      }
    });
    

2015年4月6日 星期一

Makefile

ref: http://tetralet.luna.com.tw/?op=ViewArticle&articleId=185

Makefile語法:

● 語法:

target: dependencies
<tab>Commands

target:  要建立的檔案
  make在編譯時,會比較檔案時間,決定是否重新建立target
  若該項目並非檔案,則為fake項目,而不會建立target檔案。(利用 .PHONY來指定fake項目)

dependencies: make根據這些項目決定是否重新編譯
  建立target前,必定先檢查的項目。可以不指定。

commands: 建立的指令
  必定以 \Tab 開頭(Tab開頭的都會被視為Shell script)
  每條command會啟動一個新的Shell,可以用; 將指令寫在同一行,或是 &&

● PHONY:

.PHONY: clean
clean:
<tab>rm *.o

  不論檔案時間必定執行,不會建立target

● 特別字元:

  @: 不顯示執行的命令
  -:   即使指令出錯,也不中斷make

.PHONY: clean
clean:
    @echo "Clean..."
    -rm *.o

● 隱性法則:

foo.o: common.h
    gcc -c foo.c

由於產生foo.o的指令就是foo.c,因此在make中可以簡化為:

foo.o: common.h

也可以用空白指令避免make利用隱性法則編譯
foo.o: common.h
<tab>

● 註解:

以#開頭即為註解

● 變數宣告:(macro)

利用=指定
target = foo
$(target): command
<tab>gcc -o $(target) foo.c

●Make參數:

可以用參數蓋過makefile裡的參數
make CFLAGS="-g -O2"

可以在make後接要重新建立的target
make clean



2015年3月31日 星期二

[OpenGL]Visual studio 環境設定與Error隨手記


1. visual studio 製作執行檔:
將debug模式調整為release模式


ref: https://sites.google.com/site/sjdsalg/materials/program/generateexe


2. 增加library和 link:


ref : https://social.msdn.microsoft.com/Forums/vstudio/en-US/a494abb8-3561-4ebe-9eb0-6f644a679862/visual-studio-2010-professional-how-to-add-include-directory-for-all-projects?forum=vcgeneral

3. Error: 'C:\Windows\SysWOW64\ntdll.dll'。找不到或無法開啟 PDB 檔案。



ref: http://vs-imaxlive.blogspot.tw/2013/06/cwindowssyswow64ntdlldll-pdb.html


4. Error: error LNK2001: unresolved external symbol __imp____glewBindBuffer

確定glew.lib在有在library中
(glew32.lib)

ref : http://stackoverflow.com/questions/16390078/build-error-when-trying-to-run-an-opengl-example-in-vc

2015年3月15日 星期日

Regular Expression-javascript

可以參考
http://www.w3schools.com/jsref/jsref_obj_regexp.asp

● /pattern/modifiers
  ○ pattern
    ◎ 運算元:
      [abc]:找到有abc字元(a或b或c)
      [^abc]:不包含abc字元
      a|b    :找到a或b
      n+    :找到n至少一次
      n*    :找到n 零次或一次以上
      n?    :找到n 零次或一次
   
   
    ◎ 特殊符號:
      \w :word-character (a-z, A-Z, 0-9,_)
      \W:非word-character
      \d :digit (0-9)
      \D:非digit
      \s :空白
      \S:非空白
      \b:在開頭或結尾
      \B:不在開頭或結尾
      \n:換行符號
      \r: carriage return
      \t: tab
   

  ○ modifiers
     i: 忽略大小寫
     g: 找出所有pattern,而非只找到一個就停
     m: multiline matching,和換行有關

● javascript RegExp Object:
  ○建構:
    var res = new RegExp(pattern, modifiers);

  ○Method:
    1. exec()
    2. test():  match時回傳true,否則回傳false
    3. toString()
e.g.
  var res = new RegExp(/[2-9]/g);
  if (res.test(input_txt.value))
  {
    alert("Sorry! " + input_txt.value + " is not accepted");
    clear_in();
    return;
  }
● replace():  (String method)
1.  str.replace("str1", "str2"):str1被取代為str2
2.  str.replace(/pattern/modifiers, "str1"):match的pattern取代為str1
3.  str.replace(res, "str1"):利用ResExp object,將match到的pattern取代為str1
4. 利用$1可以取得()中match到的pattern  (一定要用小括號)
e.g. (將2進位數字轉換成number) 
  str.replace(/([0-1]+)/g, "parseInt(\"$1\",2)")
  eval(str)

● test($str):  (regexp method)
  用來測試string是否包含pattern(回傳true或false)
e.g.
 var res = new RegExp(pattern, modifier);
 var str = "...";
 res.test(str);
● match: (String method)
  用來測試string 是否包含pattern(回傳match的pattern)
e.g.
 var str = "...";
 var res = str.match(/pattern/modifier);


2015年3月12日 星期四

Cryptography and Network Security-ch8

Ch8. Encipherment using modern symmetric-key cipher

5 mode to used with modern block cipher:
1.  Electronic Codebook (ECB):每個block單獨去加密
   加密:


   解密:


2. Cipher Block Chaining (CBC):將加密後的block和下一次的plaintext做XOR再加密(第一組需要initial vector)

加密:

解密:


3. Cipher Feedback (CFB):對shift register加密,加密後再和plaintext做XOR,得到的ciphertext再傳到下一個shift register

 加密:



4. Output Feedback(OFB):和CFB類似,但是傳到下一個block的是shift register加密後的temporary register

 加密:


5. Counter (CTR):直接利用counter加密,再和plaintext做XOR
 加密:



● mode 3, 4, 5 plaintext 中一個bit計算完及可以傳送這個bit,因此類似stream cipher
● ciphertext stealing:最後兩個block可以交換順序計算,進而避免最後一個block因位數不足做padding(也就是不需要做padding)
  在ECB mode下:
    X = Ek(PN-1)              → CN = headm(X)
    Y = PN | tailn-m(X)    → CN-1 = EK(Y)

  在CBC mode下:
    U = PN-1 + CN-2      →  X = Ek(U)     →  CN = headm(X)
    V = PN | padn-m(0)   → Y = X + V      → CN-1 = Ek(Y)

ref: wiki
http://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29

2015年3月9日 星期一

Regular Expression-perl

文章轉
http://user.frdm.info/ckhung/b/re/rules.php
http://ind.ntou.edu.tw/~dada/cgi/Perlsynx.htm


/regular expression/expression modifier
● Modifiers:
  g: Match globally, i.e. find all occurrences. (搜尋全部)
  i: Makes the search case-insensitive. (區分大小寫)
  m: If the string has new-line characters embedded within it, the metacharacters ^ and $ will not work correctly. This modifier tells Perl to treat this line as a multiple line. (包含多行)
  o: Only compile pattern once.
  s: The character . matches any character except a new line. This modifier treats this line as a single line, which allows . to match a new-line character. 
  x: Allows white space in the expression.

● regular expression:
  ○特殊意義字元:
    \  跳脫字元
    ^ 以...為開頭
    . 除了換行的所有字串
    $ 以...為結尾
    | 或
    [] 搜尋誇號中字元
    () 括號

  ○ 字元數量關係:
    * 大於等於0次
    + 大於等於一次
    ? 0或1次
    {n} n次
    {n.} 至少n次
    {n, m} 最少n次,不超過m次

  ○ 特定字元:
    \r: carriage return(CR)
    \n: 換行
    \t: tab
    \w: 英文字母
    \W: 非英文字母
    \s white space
    \S non-white space
    \d: 數字
    \D: 非數字
    \b:  word boundary
    \B: non-word boundary
    \033: octal char
    \x1B: hex char


字串比對:

1. $string =~ /regular expression/expression modifier
2. if /regular expression/expression modifier

example:
(將C #define 轉換成verilog #parameter)

###read file
open($fp, "test1.c");
foreach $word (<$fp>)
{
 if ($word=~/^#define (\w+) (\d+)/)
 {
  $word =~ s/define (\w+) (\d+)\n/parameter/g;
  $word = $word . sprintf(" %s = 2'b%b\n",$1 , $2);;
  print "$word";
 }
}
close($fp);


字串取代:

s/PATTERN/REPLACEMENT/egimox



2015年3月2日 星期一

Formal language and automata - ch3

Regular language and regular grammar

Regular expression:

● definition:
 1. 元素:φ, λ, a ∈ Σ 為Regular expression
 2. 運算元:若r1, r2為Regular expression
    r1 + r2  (union)
    r1 ⋅ r2  (concatenation)
    r1*       (star-closure)
   (r1)
  均為regular expression
3. 根據有限次數的1和2造出的字串均為regular expression

● language associated with regular expression:
 1. φ is a regular expression {}  (empty set)
 2. λ is a regular expression {λ}
 3. for a ∈ Σ, a is a regular expression denote  {a}

 4. L(r1 + r2) = L(r1) ∪ L(r2)
 5. L(r1 ⋅ r2) = L(r1)L(r2)
 6. L((r1)) = L(r1)
 7. L(r1*) = (L(r1))*

● operation priority:
  star closure > concatenation > union

Regular expression and regular language:

Regular expression -> Regular language

● 所有regular expression 定義的都可以畫成nfa
1. nfa accept φ

2. nfa accept {λ}

3. nfa accept {a}

4. nfa accept L(r1 + r2)

5. nfa accept L(r1 ‧ r2)

6. nfa accept L((r1)):直接去掉括號
7. nfa accept (L(r1))*

Regular language-> Regular expression

● Generalized transition graph(GTG):一個label為regular expression的transition graph

● nfa轉成complete GTG:將所有沒有連接的edge連上並標上φ
 e.g.

轉換成
● 2 state GTG轉換成regular expression:
r = r1r2 (r4 + r3r1*r2)*

● 3 state(或以上) complete GTG轉換成regular expression:將state減少,直到剩兩個state(initial state和final state)
每次減少state時,考慮將會經過的state,將它加到graph的其他路徑上
e.g.
reduce成:

○完整procedure:
  1. 將nfa轉換成單一final state的GTG,並使它complete
  2. 若GTG state為2,直接代公式
  3. 若GTG state為3,選擇一個要刪除的state(qi)(非final 也非initial的state)
  對於另外兩個state,考慮經過qi的路線
   r1 + r2r3*r4
(均為這種type)
 4. 若GTG大於4,選擇要刪除的state,對所有state均套用 r1 + r2r3*r4找關係
     降為3個state後,再用step3

Regular grammar:

● definition:
 ○left-linear grammar:每次production左側最多只出現1個variable,variable為最左側的symbol
  e.g.:
    A →Bx
    A →x
 ○right-linear grammar:每次production左側最多只出現1個variable,variable為最右側的symbol
 ○regular grammar:left-linear 或 right-linear
 ○linear grammar:每次production左側最多只出現1個variable

● right-linear grammar 轉換成 regular language(nfa):
  variable → state
  alphabet → state轉換的label

●  regular language轉換成 right-linear grammar:
  δ(qi, aj) = qk 轉換成 qi → ajqk
  (若 qk 為final state:則轉換成qk →λ)

● regular language轉換成 left-linear grammar:
  略

● regular expression <=> dfa or nfa <=> regular grammar
  為等價,可以互相轉換


2015年2月28日 星期六

Formal language and automata - ch2

Ch2. Finite automata

Deterministic Finite Accepter(dfa)


● deterministic accepter
  ○ definition:
    M = (Q, Σ, δ, q0, F)
      Q: set of internal state
      Σ: set of symbol (input alphabet)
      δ:  Q × Σ → Q transition function   (表示state的轉換)
        e.g.  
         δ(q0, 0) = q1
         即在qstate 、當input alphbet為0時,移動到state q1
      q∈ Q: initial state
      F: set of final state

     每一步都要清楚定義(每個state都要考慮所有alphbet的可能)

  ○ operate:
     1. 一開始在initial state(q0)
     2. 每次移動(move),讀入一個input alphabet,根據讀到的input和當前的state,移動到下一個state
     3. 讀完所有input時,若在final state則為accept,否則為not accept



  ○ transition graph:
    state: 以圓圈表示
    transition function: 以箭頭表示
    input: 箭頭上的label
    initial state: 一個圓圈有一個箭頭沒有前一個state
    final state: 雙圓圈

      ※ transition graph 可以表示所有的dfa
    e.g.
      M = ({q0, q1, q2}, {0, 1}, δ, q0, {q1})
     with transition function δ:
        δ(q0, 0) = q0,   δ(q0, 1) = q1
        δ(q1, 0) = q0,   δ(q1, 1) = q2
        δ(q2, 0) = q2,   δ(q2, 1) = q1


  ○ extended transition function:
     δ(q0, a) = q1
     δ(q1, b) = q2
⇒ δ*(q0, ab) = q2

● Language and dfa:
   dfa可以接受的language即為所有dfa產生的字串的集合
   L(M) = {w ∈ Σ*: δ*(q0, w) ∈ F}

  Language L is regular language if and only if there exist a dfa M使得
    L = L(M)

Nondeterministic finite accepter (nfa)

● definition:
    M = (Q, Σ, δ, q0, F)
      和dfa類似,除了transion function不同:
      δ:  Q × (Σ ∪ λ) → 2Q transition function   (表示state的轉換)

● 和dfa不同處:
          1. transition function 對應出來為一個set,而不是單一state (next state有多種可能性)
              e.g. δ(q0, a) = {q0, q1}  
          2. transition function 第二的element可為λ                              (可不消耗alphabet切換到下一個state)
          3.  δ(q0, a) 可為empty                                                               (transition 沒有定義)
          4. 可接受的string為:只要可以停在final state的string
● extended transition function: same as dfa

● transition graph:
 
                δ*(q1, a) = {q0, q1, q2}
                δ*(q2, λ) = {q0, q2}
                δ*(q2, a) = {q0, q1, q2}

                note: 每個state本身都有一個λ cycle  (即透過λ 可在原本的state)

● language:
   nfa可以接受的language即為所有nfa產生的字串的集合
   L(M) = {w ∈ Σ*: δ*(q0, w)  ∩ F ≠ φ}
  即w可以走到final state (有一個state即可)


Equivalence of deterministic and nondeterministic finite accepter

● equivalence of finite accepter:
   two finite accepter are same
   L(M1) = L(M2)
  if both accept same language

● equivalence of nfa and dfa:
    dfa 為一種nfa
    nfa 可以轉為dfa
      利用powerset ,新的graph的vertex為nfa的powerset
  ○ nfa轉換為 dfa:
          1. 創造一個新的graph G從 {q0} 開始
          2. 對於所有G上的vertex {qi, qj, ..., ql},和一個 a ∈ Σ
              找出所有從 {qi, qj, ..., ,ql} 經過a 可以到的vertex,並標為一個新的state
          3. 重複2直到沒有新的vertex
              (必定結束,因為新的graph最多2Q |Σ| edge)
          4. 標上final state: 任何有包含原本final state的vertex在新的graph均為final state
          5. 若 λ 也accept,則q0也是final state

        e.g. 
           nfa

            第一步:


            第二步:
            完成所有vertex:
            完成圖:





Reduce the number of state

● indistinguishable/ distinguishable state:
   two state are indistinguishable if
       δ(p, w) ∈ F implies δ(q, w) ∈ F
   and
       δ(p, w) ∉ F implies δ(q, w) ∉ F
    for all w ∈ Σ*



● reducing produce :
  ○ produce mark:
     1. remove 所有無法到達的state
     2. 對所有state進行區分,分成final state和非final state (兩者為distinguishable,同set裡為distinguishable)
     3. 對所有indistinguishable state區分:
         若有 a ∈ Σ 使得兩個state p, q
            δ(p, a) = pa
            δ(q, a) = qa
       且pa 和qa為distinguishable,則p q為distinguishable


     對於所有字母a
     若p q經過接受a產生的state不再同一個set(distinguishable),則p q不是同個state (distinguishable)
     4. 重複3直到沒有新的state被區分

  ○ produce reduce: 利用procedure mark找出所有相同的state,並根據相同state建立新的dfa
     1. 找出相同state: {qi, qj,...},在新的dfa M' 中視為一個state
     2. 對於原本的dfa所有transition rule δ(p, a) = q: 找出在M'中,p 和q 所在的state p' 和q'
         建立新的transition: δ(p', a) = q'
     3. 重複2直到原本的的dfa所有transition rule完成
     4. 標示initial state: M'中,包含initial state 的state即為initial state
     5. 標示final state: M'中,包含原本dfa final state的state均為final state



2015年2月15日 星期日

Formal language and automata - ch1

Ch1. Introduction

Mathematical preliminaries and notation

● Set (集合)
 A collection of element x1, x2, x3, ..., xi without any structure other than membership
  E.g. 
   S = {0, 1, 2}
   S = {a, b, ...,z }
   S = {I : i>0, I is even}

 ○ Property: 
   ※ disjoint: S1 ∩ S2 = 空集合
   ※ subset: a set S1 is a subset of S if 所有element 均為S的 element
   ※ proper subset: (同subset不包含兩個set 相同的情況)
   ※ powerset: the set of all subset of a set S
     (每個element 都是一個集合 )
   ※ Universal set (U): set with all possible elements
   ※ Empty set (φ): the set with no element
   ※ partition: 一個set分成多個subset,每個set互disjoint
   ※ finite: element of a set is finite
   ※ infinite : element of a set is infinite
   ※ size of a set: number of element in a set

 ○ Operation: 
   ※ Union
   ※ Intersection
   ※ Difference
   ※ Complementation
   ※ Demorgan's law:
     1. -(S1 ∪ S2) = (-S1) ∩  (-S2)
     2. -(S1 ∩ S2) = (-S1) ∪ (-S2)
   ※ Cartesian product:
     S1 * S2 = {(x, y): x ∈ S1, y ∈ S2 }

● Function and relation
  ○ Function: assign a element in S1 to S2 (f: S1 -> S2)
   (S1中的element 只能有一個對應,否則為relation)
   S1: domain
   S2: range
  ○ Relation: S1中,一個element 有多個對應
   E.g. Equivalance 

● Graph and tree
  ○ Graph: a construct consist 2 set: V (vertex) , E (edge)
         Each edge is a pair of vertex
      ※ walk: a sequence of edge in the form: (vi, vj), (vj, vk), (vk, vm)
        (Edge的後一個點為下一個edge 的前一個點)
      ※ length of a walk: walk經過edge 的數量
       path: edge沒有重複的walk
      ※ simple path: 沒有點重複
      ※ cycle: 一個walk 開始和結束的vertex相同
      ※ simple cycle: 沒有點重複
      ※ loop: 一個edge 開始和結束的點相同
      ※directed graph: edge 有方向性
   ○ tree: a directed graph without cycles
      ※ root: 到任何vertex 都有一條path
      ※ leaves: 只有incoming edge
      ※ Child (vi->vj) vj 為vi的 child
       parent (vi->vj) vi 為vj的 parent
      ※ level: 從root 開始到特定vertex的path經過的edge數
      ※ height of a tree: tree 中最大的level
     
 proof of technique: 
   ○ proof of by induction
   ○ proof of by contradiction 

     

Three basic concepts

 Language:

  ○ component:
      ※ alphabet
         Σ = {a, b}


      ※ string
        w = abaaa 
       (λ : empty string)
       →substring:
       →prefix:
       →suffix:
       (注意prefix和suffix都有空字串)
       →Σ* : set of 用Σ 造的字串

       →Σ+ = Σ - {λ}

  ○ definition:
    Language(L): a subset of Σ*
    sentence: a string in L

  ○ operation:
      ※ concatenation: 將字串或元素相接
      w = a1a2a3...an ; v = b1b2b3...bm
       ⇒wv = a1a2a3...anb1b2b3...bm
      L1L2 = {xy, x ∈ L1, y ∈ L2}
      ※ reverse
       wRan...a2a1
       LR = {wR: w L}
      ※ repeat:
       wn : 重複string n次(接在後面)
      ( w0 :empty string)
       L={λ}
       L= L
      ※ length: |w|

      ※ complement
       -L = Σ* - L



      ※ star-closure
       L* = L L L2...

      ※ positive-closure
       L+ = L L2...


 Grammar:
  ○ definition:

      ※ grammar
      G = (V, T, S, P)
         V : variable (set)
         T : terminal (set)
         S : start variable 
         P : production (set)
      ※ production rule:
        x → y 
      ※ apply grammar, derive
        w = uxv
        z = uyv
        w ⇒ z (w derive z)
        w1 ⇒ w2 ⇒... wn (w1 wn)

      ※ L(G) = {w  T* : S  w}
         L(G) is the language generated by grammar G

 Automata:

  ○ essential feature:
     ※ input
     ※ storage
     ※ control unit (internal state)


  ○ deterministic automata v.s.  nondeterministic automata
    deterministic : 每次都只有一種可能性(一種move可以走)
    nondeterministic : 有多種可能性



Ref: PETER LINZ, An Introduction to formal languages and automata Fifth edition