2009年8月26日 星期三

Brute Force algorithm (暴力破解法)

時間複雜度:O(mn)

public class BruteForceAlgorithm {
public static final String T = "ABABAABBCABC";
public static final String P = "ABC";

public static void match(char[] t, char[] p)
{
for (int i = 0; i < t.length; i++)
{
char[] tmp = new char[p.length];
int index = 0;
for (int j = 0; j < p.length; j++)
{
if (i+j < t.length && t[i+j] == p[j])
{
tmp[index++] = p[j];
}
else
{
continue;
}
}

if (index == p.length)
{
System.out.println(new String(tmp));
}
}
}

public static void main(String[] args) {
match(T.toCharArray(), P.toCharArray());
}
}



The C code
void BF(char *x, int m, char *y, int n) {
int i, j;

/* Searching */
for (j = 0; j <= n - m; ++j) {
for (i = 0; i < m && x[i] == y[i + j]; ++i);
if (i >= m)
OUTPUT(j);
}
}

2009年8月25日 星期二

排序 - 2

設有三組集合,在以下每組中取出一個數
{A,B,C}
{D,E,F}
{G,H,I}
可以得到27組 {A,D,G}{A,D,H}{A,D,I}{A,E,G}{A,E,H}{A,E,I}....

public class Permutation
{
static int index = 1;
static int MAX = 3; // 用來產生 3*3, 改成4就是4*4, 5*5 6*6....
static char[] soultion = new char[MAX]; // 用來紀錄排列解.
static char[][] s = new char[MAX][MAX]; // 陣列.
static boolean[][] used = new boolean[MAX][MAX]; // 紀錄這個數字是否被使用.

static void perm(int k, int h, int n)
{
if (k == n)
{
System.out.print("序號" + (index++) + ":");
for (char s : soultion)
{
System.out.print(s + "\t");
}
System.out.println();
}
else
{
for (int i = 0; i < n; i++)
{
if (!used[h][i])
{
used[h][i] = true;
soultion[k] = s[h][i];
perm(k+1, h+1, n);
used[h][i] = false;

}
}
}
}

public static void main(String[] args)
{
// 純粹產生排列陣列字元.
System.out.println("陣列:");
int c = 65;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
used[i][j] = false;
s[i][j] = (char) (c++);
}
}
// Print 字元.
for(char[] ss : s)
{
for (char ch : ss)
{
System.out.print(ch);
}
System.out.println();
}

perm(0, 0,MAX);
}
}