2008年9月14日 星期日

程式碼高亮度過濾

本來是使用CSS對pre做出明顯的差別,但是後來覺得這樣程式碼的閱讀性還是很低,因此把syntaxhighlighter裝上。
/*Code*/
pre {
  display: block;
  font-family: 'Courier New';
  font-size: 9pt;
  overflow: auto;
  border: 1px solid #ccc;
  padding: 10px 10px 10px 21px;
  max-height: 1200px;
  line-height: 1.2em;
  letter-spacing: 0px;
  color: #000;
  background: #ccc url(code_bg.gif) left top repeat-y;
}
CSS連接碼,一定要放在編輯HTML,Head之中
<link href='你的目錄/Styles/SyntaxHighlighter.css' rel='stylesheet' type='text/css'/>
Javascript連接檔,在旁邊開一個HTML/JavaScript,名稱留白,放入即可
<script language="javascript" src="你的目錄/Scripts/shCore.js"></script>
<script language="javascript" src="你的目錄/Scripts/shBrushCSharp.js"></script>
<script language="javascript" src="你的目錄/Scripts/shBrushCpp.js"></script>
<script language="javascript" src="你的目錄/Scripts/shBrushJava.js"></script>
<script language="javascript" src="你的目錄/Scripts/shBrushPhp.js"></script>
<script language="javascript" src="你的目錄/Scripts/shBrushJScript.js"></script>
<script language="javascript" src="你的目錄/Scripts/shBrushRuby.js"></script>
<script language="javascript" src="你的目錄/Scripts/shBrushSql.js"></script>
<script language="javascript" src="你的目錄/Scripts/shBrushXml.js"></script>
<script language="javascript" src="你的目錄/Scripts/shBrushCss.js"></script>
<script language="javascript">
dp.SyntaxHighlighter.ClipboardSwf = '你的目錄/Scripts/clipboard.swf';
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

2008年9月1日 星期一

計算兩者之間花了多少時間

code
#include <iostream>

using namespace std;

int main ()
{
  time_t start,end;
  // save input string
  char szInput [256];
 
  // count start
  time (&start);
  printf ("Please, enter your name: ");
  gets (szInput);
  // count stop
  time (&end);
  // save cost time dif = end - start
  double dif = difftime (end,start);
  printf ("Hi %s.\n", szInput);
  printf ("You have taken %.2lf seconds to type your name.\n", dif );
 
  system("pause");
}

2008年8月30日 星期六

中置轉成後置

code
package javahomework;

import javax.swing.JOptionPane;

class postfix {
 private char stack[], z[];
 private int pri[] = { 0, 1, 1, 2, 2, 3 };
 private char oper[] = { '(', '+', '-', '*', '/', '^' };
 private int top, n, a;
 private String postfix = "";
 private char x[], y;

 public postfix() {
  n = 50;
  top = 0;
  a = 0;
  stack = new char[n];
  z = new char[n];
 }

 public String infix_to_postfix(String infix) {
  int i = 0, j = infix.length();
  x = infix.toCharArray();
  for (i = 0; i < j; i++) {
   switch (x[i]) {
   case '(':
    push(x[i]);
    break;
   case ')':
    y = pop();
    while (!empty() && y != '(') {
     z[a++] = y;
     y = pop();
    }
    break;
   case '+':
   case '-':
   case '*':
   case '/':
   case '^':
    y = top();
    while (pre(y) >= pre(x[i])) {
     z[a++] = pop();
     y = top();
    }
    push(x[i]);
    break;
   default:
    z[a++] = x[i];
   }
  }
  while (!empty()) {
   z[a++] = pop();
  }
  for (i = 0; i <= a - 2; i++) {

   postfix += z[i];
   postfix += " ";
  }
  return postfix;
 }

 private boolean empty() {
  return (top < 0) ? true : false;
 }

 private boolean full() {
  return (top >= n - 1) ? true : false;
 }

 private void push(char sta) {
  stack[++top] = sta;
 }

 private char pop() {
  return stack[top--];
 }

 private char top() {
  return stack[top];
 }

 private int pre(char op) {
  for (int i = 0; i < 6; i++)
   if (oper[i] == op)
    return pri[i];
  return -1;
 }

 private void check(char x, char y) {
  y = top();
  while (pre(y) >= pre(x)) {
   postfix += pop();
   y = top();
  }
  push(x);
 }

}

public class HW18 {

 public static void main(String arg[]) {
  String input = JOptionPane.showInputDialog(null,
    "Please input string (ex.1+2-3)");
  postfix p = new postfix();
  JOptionPane.showMessageDialog(null, 
    String.valueOf(p.infix_to_postfix(input)));
 }
}

2008年8月29日 星期五

簡易計算機

只計算一次 A+B 或 A-B
code
package javahomework;

import javax.swing.JOptionPane;

public class HW17 {

 static int toNumber(char array[], int begin, int end) {
  String temp = "";
  for (int i = begin; i < end; i++)
   temp += array[i];
  return Integer.parseInt(temp);
 }

 static long sum_number(String input) {
  int index = 0;
  long sum = 0;

  char a[] = input.toCharArray();
  for (int i = 0; i < a.length; i++) {
   switch (a[i]) {
   case '+': // A+B
    sum += toNumber(a, 0, i) + toNumber(a, i + 1, a.length);
    break;
   case '-': // A-B
    sum += toNumber(a, 0, i) - toNumber(a, i + 1, a.length);
    break;
   }
   index++;
  }
  return sum;
 }

 public static void main(String args[]) {
  String input = JOptionPane.showInputDialog(null,
    "Please input 1+2 or 1-2");
  JOptionPane.showMessageDialog(null, String.valueOf(sum_number(input)));
 }
}

字串大小寫轉換

code
package javahomework;

import javax.swing.JOptionPane;
import java.util.StringTokenizer;

public class HW16 {
 public static void main(String args[]) {
  String input = JOptionPane.showInputDialog(null, "");
  StringTokenizer st = new StringTokenizer(input);
  String out = "";
  while (st.hasMoreTokens()) {
   String tmp = st.nextToken();
   StringBuffer buf1 = new StringBuffer(tmp);
   StringBuffer buf2 = new StringBuffer(tmp);
   out = out + buf1.toString().toLowerCase()
     + buf2.toString().toUpperCase() + " ";
  }
  JOptionPane.showMessageDialog(null, out);
 }
}

定義一個點->圓->圓錐體->雙圓錐體

code
package javahomework;

public class HW15 {

 class Point {
  private double x, y;

  public Point() {
   x = 1.0;
   y = 1.0;
  }

  public Point(double n1, double n2) {
   x = n1;
   y = n2;
  }

  public double getX() {
   return x;
  }

  public double getY() {
   return y;
  }
 }

 class Circle{
  private double r;
  private Point p;
  public double pi = 3.1415926;

  Circle() {
   r = 1.0;
  }

  public double findArea() {
   return r * r * pi;
  }

  public double findlength() {
   return r * pi * 2;
  }

  public void set(double n,Point p) {
   r = n;
  }

  public double get_r() {
   return r;
  }
  
  public Point get_Point(){
   return p;
  }
  
  public void set_Point(Point p){
   this.p = p;
  }
 }

 class Cone extends Circle {
  private double r = super.get_r();
  private double h;

  Cone() {
   h = 1.0;
  }

  Cone(double n1, double n2) {
   r = n1;
   h = n2;
  }

  public void set(double n1, double n2) {
   r = n1;
   h = n2;
  }

  public double getR() {
   return r;
  }

  public double getH() {
   return h;
  }

  public double findVolume() {
   return (pi * r * r * h) / 3;
  }

  public double findFaceArea() {
   return (Math.pow((r * r) + (h * h), 0.5)) * 2 * pi;
  }

 }

 class DouleCone extends Cone {
  private double r = super.getR();
  private double h = super.getH();

  public double findDoublejVolume() {
   return super.findVolume() * 2;
  }

  public double findDoubleH() {
   return h * 2;
  }

  public double findDoubleVolume() {
   return super.findVolume() * 2;
  }

  public double findDoubleFaceArea1() {// 漏斗
   return super.findFaceArea() * 2;
  }

  public double findDoubleFaceArea2() {// 兩邊尖
   return (super.findFaceArea() * 2) - (r * r * pi) * 2;
  }
 }
}

定義一個父矩形,子長方體並繼承

code
package javahomework;

public class HW14 {

 class Rectangle {
  private double length1, length2;

  public Rectangle() {
   length1 = 1.0;
   length2 = 1.0;
  }

  public Rectangle(double n) {
   length1 = n;
   length2 = n;
  }

  public Rectangle(double n1, double n2) {
   length1 = n1;
   length2 = n2;
  }

  public void set(double n1, double n2) {
   length1 = n1;
   length2 = n2;
  }

  public double getL1() {
   return length1;
  }

  public double getL2() {
   return length2;
  }

  public double findArea() {
   return length1 * length2;
  }

  public double find4Length() {
   return (length1 + length2) * 2;
  }
 }

 class AdRectangle extends Rectangle {
  private double hight;

  AdRectangle() {
   hight = 1.0;
  }

  AdRectangle(double n1, double n2, double n3) {
   super(n1, n2);
   hight = n3;
  }

  public void set(double n1, double n2, double n3) {
   super.set(n1, n2);
   hight = n3;
  }

  public double findVolume() {
   return super.findArea() * hight;
  }

  public double findArea() {
   return super.getL1() * super.getL2();
  }

  public double findFaceArea() {
   return super.findArea() * 2 + super.getL1() * hight * 2
     + super.getL2() * hight * 2;
  }
 }
}

計算1+1/1+1/2!+1/3!+1/4!

code
package javahomework;

import javax.swing.JOptionPane;

public class HW13 {
 static double Count(int n) {
  if (n == 0 || n == 1)
   return 1;
  else
   return n * (Count(n - 1));
 }

 public static void main(String arg[]) {
  int input;
  float ans = 0;
  input = Integer.parseInt(JOptionPane.showInputDialog(null,
    "How much do you want to count?"));
  for (int i = 0; i < input; i++)
   ans += 1 / (Count(i));
  ans -= (ans % 0.000001);
  JOptionPane.showMessageDialog(null, "Number is " + ans);
 }
}

算出PI

注意:要計算很久,會把CPU資源吃光光
code
package javahomework;

import javax.swing.JOptionPane;

public class HW12 {
public static void main(String arg[]) {
double p = 0, input = 1e10;
int x = -1;
for (double i = 0; i < input; i++) {
x *= -1;
// 4x(1-1/3+1/5-1/7+1/9...)
p += 4 * ((1 / (2 * i + 1)) * x);
}
p -= p % 0.0000000001;
JOptionPane.showMessageDialog(null, "PI is " + p);
}
}

計算產生第幾個新的類別

技巧:設定變數為static
code
package javahomework;

import javax.swing.JOptionPane;

class TestC {
 static int count = 0;

 public static TestC getInstance() {
  TestC x = new TestC();
  count++;
  return x;
 }

 public static String get_count() {
  return String.valueOf(count);
 }
}

public class HW11 {
 public static void main(String args[]) {
  TestC c1 = TestC.getInstance();
  TestC c2 = TestC.getInstance();
  TestC c3 = TestC.getInstance();
  JOptionPane.showMessageDialog(null, TestC.get_count());
 }

}

用類別寫陣列堆疊

code
package javahomework;

import javax.swing.JOptionPane;

class Queue {
 int Q[], front, rear, newrear, MaxSize;
 String screen = "";

 public Queue() {
  MaxSize = 5;
  Q = new int[MaxSize];
  front = rear = -1;
 }

 public void add(int x) {
  if (isfull())
   JSM("Queue is full");
  else {
   Q[rear = newrear] = x;
   JSM("Add " + x);
  }
 }

 public void delete() {
  if (isempty())
   JSM("Queuq is empty");
  else
   front = (front + 1) % MaxSize;
  JSM("Delete " + Q[front]);
 }

 public boolean isempty() {
  if (rear == front)
   return true;
  else
   return false;
 }

 public boolean isfull() {
  newrear = (rear + 1) % MaxSize;
  if (front == newrear)
   return true;
  else
   return false;
 }

 private void JSM(String messeng) {
  JOptionPane.showMessageDialog(null, messeng);
 }

 public void dump() {
  if (isempty())
   JSM("Queuq is empty");
  else
   for (int i = 0; i < Q.length; i++)
    screen = screen + Q[i] + " ";
  JSM(screen);
 }
}

public class HW10 {
 public static void main(String args[]) {
  Queue q1 = new Queue();
  q1.add(1);
  q1.add(2);
  q1.delete();
  q1.add(3);
  q1.add(4);
  q1.delete();
  q1.add(5);
  q1.add(6);
  q1.add(7);
  q1.dump();
 }

}

利用類別特性定義一個圓錐體,並且可以算出體積、表面積

code
package javahomework;

public class HW09 {
 public static void main(String args[]) {
  Cone r1 = new Cone();
  Cone r2 = new Cone(10.0);
  Cone r3 = new Cone(15.0, 20.0);
  System.out.println("Volume is " + r1.volume() + " FaceArea is "
    + r1.facearea());
  System.out.println("Volume is " + r2.volume() + " FaceArea is "
    + r2.facearea());
  System.out.println("Volume is " + r3.volume() + " FaceArea is "
    + r3.facearea());
 }

}

class Cone {
 double r, h;
 double pi = 3.14;

 Cone(double a, double b) {
  r = a;
  h = b;
 }

 Cone() {
  r = 1.0;
  h = 1.0;
 }

 Cone(double a) {
  r = a;
  h = a;
 }

 double volume() {
  return (pi * r * r * h) / 3;
 }

 double facearea() {
  return (Math.pow((r * r) + (h * h), 0.5)) * 2 * pi;
 }
}

利用亂數產生兩個二維陣列A,B計算出C=A*B

code
package javahomework;

public class HW08 {
 public static void main(String arg[]) {
  int a[][] = new int[2][2];
  int b[][] = new int[2][2];
  int c[][] = new int[2][2];
  for (int i = 0; i < a.length; i++)
   for (int j = 0; j < a[i].length; j++)
    a[i][j] = (int) (Math.random() * 10);
  for (int i = 0; i < b.length; i++)
   for (int j = 0; j < b[i].length; j++)
    b[i][j] = (int) (Math.random() * 10);
  for (int i = 0; i < a.length; i++)
   for (int j = 0; j < b[i].length; j++)
    for (int k = 0; k < b[j].length; k++)
     c[i][j] = c[i][j] + a[i][k] * b[k][j];

  for (int i = 0; i < c.length; i++) {
   for (int j = 0; j < c[i].length; j++)
    System.out.print(c[i][j] + " ");
   System.out.print("\n");
  }
 }
}

輸入一個一級陣列,利用氣泡排序法排序

code
package javahomework;

import javax.swing.JOptionPane;

public class HW07 {
 public static void main(String args[]) {
  int a[] = new int[10];
  String screen = "Sort ";
  for (int x = 0; x < a.length; x++)
   a[x] = Integer.parseInt(JOptionPane.showInputDialog(null,
     "Input Number"));
  bubblesort(a);
  for (int y = 0; y < a.length; y++)
   screen = screen + a[y] + " ";
  JOptionPane.showMessageDialog(null, screen);
 }

 public static void bubblesort(int n[]) {
  for (int i = 0; i < n.length - 1; i++)
   for (int j = 0; j < n.length - 1; j++)
    if (n[j + 1] > n[j]) {
     int tmp = n[j];
     n[j] = n[j + 1];
     n[j + 1] = tmp;
    }
 }
}

輸入一個數,計算其檢查碼

code
package javahomework;

import javax.swing.JOptionPane;

public class HW06 {
 public static void main(String args[]) {
  int input;
  input = Integer.parseInt(JOptionPane.showInputDialog(null, ""));
  JOptionPane.showMessageDialog(null, "Check Number is " + Number(input));
 }

 static int Number(int n) {
  return ((ADD(n) % ADD2(n)) % 10);
 }

 static int ADD(int n) {
  if (n < 10)
   return (n * n);
  else
   return (ADD(n / 10) + ADD(n % 10));
 }

 static int ADD2(int n) {
  if (n < 10)
   return n;
  else
   return (ADD2(n / 10) + ADD2(n % 10));
 }

}

找出1~2000中所有的Perfect number

Perfect number 是指某一個數,其因數相加會等於其數
code
package javahomework;

import javax.swing.JOptionPane;

public class HW05 {
 public static void main(String args[]) {
  String Screen = "The PerfectNumber is ";
  for (int j = 4; j < 2000; j++) {
   if (AD(j) == j)
    Screen = Screen + j + ",";
  }
  JOptionPane.showMessageDialog(null, Screen);
 }

 static int AD(int n) {
  int ans = 1;
  for (int i = 2; i < n; i++) {
   if (n % i == 0)
    ans = ans + i;
  }
  return ans;
 }
}

輸入一個數,算出所有數的總和

把輸入的數字一直除以10,剩下10以下的餘數再相加即可

code
package javahomework;

import javax.swing.JOptionPane;

public class HW04 {
    public static void main(String args[])
    {
       int input;
       input = Integer.parseInt(JOptionPane.showInputDialog(null,"Input Number"));
       JOptionPane.showMessageDialog(null,"The sum of "+input+" is "+ADD(input));
    }
    static int ADD(int n)
    {
        if (n<10)
            return n;
        else
            return (ADD(n/10)+ADD(n%10));
    }

}

2008年8月27日 星期三

謎之聲特效

自己寫了簡單的CSS,目的只是讓自己看起來很爽而已。
.stalk {
 color: rgb(204, 204, 204);
}
.stalk:hover{
 color: rgb(0, 0, 0);
}
滑鼠移上去會字體會變成黑色,沒移上去就是淡灰色。

2008年8月19日 星期二

求出第一個大於100000的費式數列是第幾項

用遞迴的寫法
/**
  * FIB use recursive
  * 
  * @param big_number
  * @return big than big_number is
  */
 public static int fib_slow(long big_number) {
  long f = 1;
  int ans = 0;
  for (long i = 0; f < big_number; i++) {
   f = fib(i);
   ans++;
  }
  return ans;
 }

 public static long fib(long n) {
  if (n == 0 || n == 1)
   return n;
  else
   return (fib(n - 2) + fib(n - 1));
 }
用單一迴圈的寫法,所花的時候只有O(n)
/**
  * FIB not use recursive
  * 
  * @param number
  * @return big than big_number is
  */
 public static int fib_quick(long number) {
  long a, b, c;
  /* A[0]=0,A[1]=1 has been count in first time, so ans=2*/
  int ans = 2;
  a = 0;
  b = 1;
  c = a + b;
  while (c < number) {
   /* A[n+2]=A[n]+A[n+1]; */
   c = a + b;
   /* next ...., let A be a=A[n+1],b=A[n+2] */
   a = b;
   b = c;
   ans++;
  }
  return ans;
 }
code

最大公因數 Greatest common divisor

code
package javahomework;

import javax.swing.JOptionPane;

public class HW01 {
 /**
  * Main
  * 
  * @param args
  */
 public static void main(String args[]) {
  int number1 = Integer.parseInt(JOptionPane.showInputDialog(null,
    "Please Input Number1 "));
  int number2 = Integer.parseInt(JOptionPane.showInputDialog(null,
    "Please Input Number2 "));
  JOptionPane.showMessageDialog(null, "GCD is " + GCD(number1, number2));
 }

 /**
  * Retrun GCD
  * 
  * @param number1
  * @param number2
  * @return GCD
  */
 static int GCD(int number1, int number2) {
  if (number1 % number2 == 0)
   return number2;
  else
   return (GCD(number2, number1 % number2));
 }
}

簡單運算元多載

MyString.cpp code
#include "stdafx.h"
#include "MyString.h"
#include <string.h>

MyString &MyString::operator+ (const char* str)
{
 static MyString backup;
 backup.assign(this->Getstring());
 backup.append(str);
 
 return backup;
}
MyString &MyString::operator+ (MyString &str)
{
 static MyString backup;
 backup.assign(this->Getstring());
 backup.append(str.Getstring());
 
 return backup;
}
MyString &MyString::operator= (const char *str)
{
 this->assign(str);
 return *this;
}
MyString &MyString::operator= (MyString &str)
{
 this->assign(str.Getstring());
 return *this;
}

MyString::MyString(const char *str)
{
 if(str==NULL)
 {
  Data=NULL;
 }
 else
 {
  Data=new char [strlen(str)+1];
  strcpy(Data,str);
 }
}

MyString::~MyString()
{
   if(Data!=NULL)
 delete [] Data;
   Data=NULL;
}

void MyString::assign(const char *str)
{
   if(Data!=NULL)
 delete [] Data;
   Data=NULL;

   Data=new char [strlen(str)+1];
   strcpy(Data,str);
}

void MyString::clean()
{
   if(Data!=NULL)
 delete [] Data;
   Data=NULL;
}

int MyString::length()
{
 return strlen(Data);
}

const char* MyString::Getstring()
{
 return Data;
}

void MyString::append(const char *str)
{
 if(Data==NULL)
  assign(str);
 else
 {
  char *Backup=new char [length()+1];
  strcpy(Backup,Data);
  delete [] Data;
  Data=new char [strlen(Backup)+strlen(str)+1];
  strcpy(Data,Backup);
  strcat(Data,str);
  delete [] Backup;
 }
}


char *MyString::token(char *str)
{
 if(Data==NULL) 
  return NULL;

    char *result=new char [length()+1];
 int count=0;
 

 for(int i=0;i<length();i++)
 {
  // 檢查是否有token
  bool found=false;
   for(unsigned int j=0;j<strlen(str);j++)
  {
   if(Data[i]==str[j])
   {   //如果有找到 直接跳出 並 found=true
    found=true; 
    break;
   }
  }

   if(!found) //沒找到表示要把目前處理的字元放到 result內
      result[count++]=Data[i];
   else
   {
    result[count]='\0';
    // Backup the Left String
    char *backup=new char[length()-count+1];
    int index=0;
    strcpy(backup,&Data[count+1]);

    //把剩下的重新給Data
    delete [] Data;
    Data=new char[strlen(backup)+1];
    strcpy(Data,backup);
    delete [] backup;

    return result;
   }
 }
    result[count]='\0';
 delete [] Data;
 Data=NULL;
 return result;
}

簡單壓縮程式

Run_Length.h code
#ifndef Run_Length
#define Run_Length

#include <fstream>

using std::cout;
using std::endl;
using std::cerr;
using std::ios;
using std::fstream;
using std::ifstream;
using std::ofstream;
using std::string;

int Run_Length_Code(const char *input_filename, const char *output_filename )
{
 fstream f_in; //設定輸入流 
 fstream f_out;//設定輸出流 
 
 //開檔 並設為輸入和二位元讀取 
    f_in.open(input_filename,ios::binary|ios::in); 
 if( !f_in )  //輸入檔錯誤
 {
  cerr << "Input file ERROR!! " << endl;
  system("PAUSE");
  exit(1);
 }
 
 //開檔 並設為輸出和二位元寫入 
    f_out.open(output_filename,ios::binary|ios::out);
 if( !f_out ) //輸出檔錯誤 
 {
  cerr << "Output file ERROR!! " << endl;
  system("PAUSE");
  exit(1);
 }

 char temp,n,num,data,next;
 unsigned int Total_in=0,Total_out=0;
 int cont=0;
 //檔頭資訊檔 
 char ch[12] = {0, 255, 67, 72, 55, 95, 67, 83, 73, 69, 0, 255};
 char head[12];

    //檢查檔頭 是否已經壓縮過 
 int count = 0;
 bool check = false;
 for(int i = 0; i < 12; i++)
 {
  f_in.read(&head[i],1);
  if(ch[i] == head[i]) count++;
 }
 if(count==12) check = true;
 
 f_in.close(); //關檔 
 f_in.open(input_filename,ios::binary|ios::in);// 開檔 
 
 if (check) //有檔頭表示是壓縮過的 
 { //解壓縮 
 cout << "The "<< input_filename <<" is a uncompressed file, compressing …";
 for (int i=0;i<sizeof(ch);i++)
  f_in.read(&temp,1);
  while( 1 )
   {
   f_in.read(&n,1);
   if( !f_in ) break; //如果沒有資料就跳出  
   Total_out+=n; //計總共傳了多少 
   Total_in+=n;  //計總共讀了多少 
   f_in.read(&temp,1);
   for(int i = 0; i < n; i++)
     f_out.write(&temp,1);
   }
    } 
 else
 { //壓縮 
 bool ok=true;
 cout << "The "<< input_filename <<" is a compressed file, decompressing …\n";
 f_out.write(ch,sizeof(ch)); //寫入壓縮檔頭 
 while ( 1 )
 {
  if (ok) {
   f_in.read(&data,1); //讀入資料 
   Total_in++; //讀檔計數 
  }
  if( !f_in ) break;//若沒有資料就跳出 
  cont = 1; //重新開始數 

  while ( 1 )
  {
      f_in.read(&next,1);  
      Total_in++; //讀檔計數 
   if( !f_in )
            { 
    if(cont < 256) // 如果計數沒有大於256 
    {
      num = cont; 
     f_out.write(&num,1);
     f_out.write(&data,1);
     break;
    }
    else //看超過幾次256次 
    {      
     for(int i = 0; i < cont / 255; i++)
     {
       num = 255; 
      f_out.write(&num,1);
      f_out.write(&data,1);
      Total_out+=256;
     }
     //再把剩下的數字輸出
     num = cont % 255;;
     f_out.write(&num,1);
     f_out.write(&data,1);
     Total_out+=num;
     break;
    }//end of else 
   }//end of if(!f_in)
            //f_in.read(&nextdata,1); //讀入下一筆資料
            if ( data == next )
               cont++; //當資料相同的時候 計數 
            if ( data != next )
            {
        ok=false;
     if (cont < 256) // 如果計數沒有大於256
      {
        num = cont;  
                  f_out.write(&num,1);//輸出次數 
                  f_out.write(&data,1); // 輸出資料
                  Total_out+=2;
                  data = next;
                  break;
     }
    else {
      //看超過幾次256次
     for(int i = 0; i < cont / 255; i++)
     {
       num = 255; 
      f_out.write(&num,1);
      f_out.write(&data,1);
      Total_out+=256;
     }
     //再把剩下的數字輸出
     num = cont % 255;
     f_out.write(&num,1);
     //f_out.write(&data,1);
     data = next;
     Total_out+=num;
     break;
        }//end of else
            }//end of if !=
  }//end of while
 }//end of while
    }//end of 壓縮 
    
    f_in.close(); //關輸入檔 
    f_out.close(); //關輸出檔
    return (Total_in-Total_out)/Total_in*100;
}

#endif

main.cpp code
#include <iostream>
#include "Run_Length.h"

using namespace std;

int main(int argc, char *argv[])
{
 char in[255],out[255]; //存檔案的名子
 cout << "Please enter input filename : ";
 cin >> in; //輸入檔名 
 cout << "Please enter output filename : ";
 cin >> out;//輸出檔名 

 int Rate;
    Rate=Run_Length_Code(in,out); //壓縮檔案or解壓縮 

 cout << "Finished. The compression rate : " << Rate << "%." << endl;
 
    system("PAUSE");
    return EXIT_SUCCESS;
}

LinkList in C++

main.cpp
#include <iostream>
using std::cin;
using std::endl;


#include "list.h"
int main()
{
List< int > L;
int inputmax,front,back,tmpF,tmpB;
bool ok;
cout << "How much number do you want to input? ";
cin >> inputmax;
for (int i=0 ; i<inputmax; i++)
{
cout << "please enter "<< i+1 <<"th number =>";
cin >> back;
if (i==0) { //第一次直接加入
L.insertAtBack(back);
L.print();
}
else if (i==1) { //第二次比較大加在前 比較小加在後
L.getFront(front);
if (front>back) { //加在前
L.insertAtFront(back);
L.print();
}
else {    //加在後
L.insertAtBack(back);
L.print();
}
}
else {
L.getFront(tmpF); //取得最前面的資料
L.getBack(tmpB); //取得最後面的資料
//    cout << tmpF << " " << tmpB;
if (back<tmpF) {
L.insertAtFront(back);
L.print();
}
else if (tmpB<back) {
L.insertAtBack(back);
L.print();
}
else {
L.insert(back);
L.print();
}
}
}
return 0;
}

http://pastie.org/255668

list.h
#ifndef LIST_H
#define LIST_H

#include <iostream>
using std::cout;

#include <new>
#include "listnode.h"

template< class NODETYPE >
class List {
public:
List();
~List();
void insertAtFront( const NODETYPE & );
void insertAtBack( const NODETYPE & );
void insert(const NODETYPE &);
bool getFront( NODETYPE & );
bool getBack ( NODETYPE & );
bool removeFromFront( NODETYPE & );
bool removeFromBack( NODETYPE & );
bool isEmpty() const;
void print() const;
private:
ListNode< NODETYPE > *firstPtr;
ListNode< NODETYPE > *lastPtr;
ListNode< NODETYPE > *getNewNode( const NODETYPE & );
};
template< class NODETYPE >
List< NODETYPE >::List()
: firstPtr( 0 ),
lastPtr( 0 ) {}
template< class NODETYPE >
List< NODETYPE >::~List()
{
if ( !isEmpty() ) {
cout << "Destroying nodes ...\n";
ListNode< NODETYPE > *currentPtr = firstPtr;
ListNode< NODETYPE > *tempPtr;
while ( currentPtr != 0 ) {  // delete remaining nodes
tempPtr = currentPtr;
cout << " " << tempPtr->data ;
currentPtr = currentPtr->nextPtr;
delete tempPtr;
}
}
cout << "\nAll nodes destroyed\n";
}
template< class NODETYPE >   //insertAtFront
void List< NODETYPE >::insertAtFront( const NODETYPE &value ) {
ListNode< NODETYPE > *newPtr = getNewNode( value );
if ( isEmpty() )
firstPtr = lastPtr = newPtr;
else {
newPtr->nextPtr = firstPtr;
firstPtr = newPtr;
}
}
template< class NODETYPE >   //insert
void List< NODETYPE >::insert( const NODETYPE &value ) {
ListNode< NODETYPE > *newPtr = getNewNode( value );
ListNode< NODETYPE > *tempPtr = firstPtr;
if ((newPtr->data)<(firstPtr->nextPtr->data)){
newPtr->nextPtr = firstPtr->nextPtr;
firstPtr->nextPtr = newPtr;
}
else {
while (!((newPtr->data)<(tempPtr->nextPtr->data))) {
tempPtr = tempPtr->nextPtr;
}
newPtr->nextPtr = tempPtr->nextPtr;
tempPtr->nextPtr = newPtr;
}
}
template< class NODETYPE >   //insertAtBack
void List< NODETYPE >::insertAtBack( const NODETYPE &value ) {
ListNode< NODETYPE > *newPtr = getNewNode( value );
if ( isEmpty() )
firstPtr = lastPtr = newPtr;
else {
lastPtr->nextPtr = newPtr;
lastPtr = newPtr;
}
}
template< class NODETYPE >   //romoveFromFront
bool List< NODETYPE >::removeFromFront( NODETYPE &value ) {
if ( isEmpty() )
return false;
else {
ListNode< NODETYPE > *tempPtr = firstPtr;
if ( firstPtr == lastPtr )
firstPtr = lastPtr = 0;
else
firstPtr = firstPtr->nextPtr;
value = tempPtr->data;
delete tempPtr;
return true;
}
}
template< class NODETYPE >   //romoveFromBack
bool List< NODETYPE >::removeFromBack( NODETYPE &value ) {
if ( isEmpty() )
return false;
else {
ListNode< NODETYPE > *tempPtr = lastPtr;
if ( firstPtr == lastPtr )
firstPtr = lastPtr = 0;
else {
ListNode< NODETYPE > *currentPtr = firstPtr;
while ( currentPtr->nextPtr != lastPtr )
currentPtr = currentPtr->nextPtr;
lastPtr = currentPtr;
currentPtr->nextPtr = 0;
}
value = tempPtr->data;
delete tempPtr;
return true;
}
}
template< class NODETYPE >   //getFront
bool List< NODETYPE >::getFront( NODETYPE &value ) {
ListNode< NODETYPE > *tempPtr = firstPtr;
value = tempPtr->data;
return true;
}
template< class NODETYPE >   //getBack
bool List< NODETYPE >::getBack( NODETYPE &value ) {
ListNode< NODETYPE > *tempPtr = lastPtr;
value = tempPtr->data;
return true;
}
template< class NODETYPE >   //check isEmpty
bool List< NODETYPE >::isEmpty() const {
return firstPtr == 0;
}

template< class NODETYPE >   //getNewNode
ListNode< NODETYPE > *List< NODETYPE >::getNewNode(
const NODETYPE &value ) {
return new ListNode< NODETYPE >( value );
}

template< class NODETYPE >   //print Link
void List< NODETYPE >::print() const {
if ( isEmpty() ) {
cout << "The list is empty\n\n";
return;
}
ListNode< NODETYPE > *currentPtr = firstPtr;
cout << "list: ";
while ( currentPtr != 0 ) {
cout << currentPtr->data << ' ';
currentPtr = currentPtr->nextPtr;
}
cout << "\n";
}
#endif

!!listnode.h
#ifndef LISTNODE_H
#define LISTNODE_H

template< class NODETYPE >
class List;

template< class NODETYPE >
class ListNode {
friend class List< NODETYPE >;
public:
ListNode( const NODETYPE & ); 
NODETYPE getData() const;  //getDate
private:
NODETYPE data;     //save data
ListNode< NODETYPE > *nextPtr;
};

template< class NODETYPE >
ListNode< NODETYPE >::ListNode( const NODETYPE &info )
: data( info ),
nextPtr( 0 ) {}

template< class NODETYPE >
NODETYPE ListNode< NODETYPE >::getData() const {
return data;
}

#endif

http://pastie.org/255677

QueueSort in C++

main.cpp
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

#include "q2.h"

int main() {
int inputmax,tmp,check;
inputmax=5;
bool ok;
Queue QueueSort;
#ifdef DEBUGs  //Debug 
QueueSort.add(8);
QueueSort.add(1);

QueueSort.around();
QueueSort.around();
QueueSort.around();
QueueSort.around();
QueueSort.around();
// cout << "del is:"<<QueueSort.del()<<"\n";
cout << "getfront:" << QueueSort.getfront() 
<< "getrear" << QueueSort.getrear(); 
#endif 
for (int i=0 ; i<inputmax; i++) {
ok=true;
cout << "please enter "<< i+1 <<"th number =>";
cin >> tmp;
if (i < 2) {
QueueSort.add(tmp);
QueueSort.pr();
} else {
//            QueueSort.del(check);
check=QueueSort.getfront();
//   tmp=QueueSort.getrear();
#ifdef DEBUG //Debug
cout << "front:" << check << " rear:" << tmp << " ";
QueueSort.pr();
#endif
while (ok) {
if (check < tmp) { //front < input
#ifdef DEBUG //Debug
cout << "add-cin check:" << check << " tmp:" << tmp << " ";
QueueSort.pr();
#endif
QueueSort.add(tmp);
QueueSort.pr();
ok=false;
} else {
QueueSort.around();
//                    QueueSort.add(tmp);
QueueSort.pr();
}
check=QueueSort.getfront();
}
#ifdef DEBUGs //Debug
int aa;
cin >> aa;
#endif
cout << "Sort Number:\n";
do  {
if (QueueSort.getfront()>QueueSort.getrear()) {
QueueSort.pr();
//break; 
} else {
QueueSort.around();
QueueSort.pr();
}
} while (QueueSort.getfront()<QueueSort.getrear());
}
}
return 0;
}

http://pastie.org/255656


q2.h
#ifndef QUEUE_H
#define QUEUE_H

class Queue {
public:
Queue();
void qFull();
void qEmpty();
void add(const int x);
int del();
int getfront();
int getrear();
void pr();
void around();
bool IsFull();
bool IsEmpty();
private:
int front,rear;
int q[6];
int max;

};

Queue::Queue()
{
front=-1;
rear=-1;
max=6;
for (int i=0;i<max;i++)
q[i]=0;
}

void Queue::qFull() {
cout << "\nQueue is Full!!\n";//傳出滿了
}
void Queue::qEmpty() {
cout << "\nQueue is Empty!!\n";//傳出空的
}
inline void Queue::add(const int x) {
#ifdef DEBUG //Debug
cout << "before add() front:" << front << " rear:" << rear << " ";
pr();
#endif
int newrear=(rear+1)%max; //測滿了沒
if (front==newrear)
qFull();    //如果滿了就不加
else
q[rear=newrear]= x; //若沒有就加入
#ifdef DEBUG //Debug
cout << " after add() front:" << front << " rear:" << rear << " ";
pr();
#endif
}
inline bool Queue::IsFull() {
if (rear==(max-1)) return true;
else return false;
}
inline bool Queue::IsEmpty() {
if (front==rear) return true;
else return false;
}
inline int Queue::del() {
#ifdef DEBUG //Debug
cout << "before del() front:" << front << " rear:" << rear << " ";
pr();
#endif
int x;
if (front==rear) {
qEmpty();
return 0;
}
else {
front=(front+1)%max;
x = q[front];  //傳回值
q[front]=0;   //清除
}
#ifdef DEBUG //Debug
cout << " after del() front:" << front << " rear:" << rear <<" ";
pr();
#endif
return x;
}

int Queue::getfront() {
int newfront=(front+1)%max;
#ifdef DEBUG //Debug
cout << "getfront() newfront:" << newfront << " rear:" 
<< rear << " q:" << q[newfront] <<"\n";
#endif
return q[newfront];
}
int Queue::getrear() {
#ifdef DEBUG //Debug
cout << "getrear()  front:" << front << " rear:" 
<< rear << " q:"<<q[rear] <<"\n";
#endif
return q[rear];
}
inline void Queue::pr() { //print from first to rear
cout << "List:";
int newfront=(front+1)%max;
int newrear=(rear+1)%max;
for (int i=0;i<max-1;i++) {
cout << " " << q[newfront];
newfront=(newfront+1)%max;
//  cout << " " <<q[i];
}

cout << "\n";
}
void Queue::around() { //旋轉
#ifdef DEBUG //Debug 
cout << "Start Around\n";
#endif
add(del());
#ifdef DEBUG //Debug 
cout << "End Around\n";
#endif
}
#endif

http://pastie.org/255658

2008年7月22日 星期二

從文字檔讀入並讀出特定字串那行

只做簡單的比對,若要變更只要更改正規式裡面的條件就好

不過應該有比較簡易的寫法吧?目前是這樣比較容易閱讀 :p

filename = 'input.txt'
output = 'output.txt'

if File.file? filename
  p 'Reading File...'
  open(filename) do |f|
    open(output, 'a') do |out|  
  p 'Writting File...'
      f.to_a.each do |x|
        if x =~ /String!/
          out.puts x
        end
      end

    end # end of output   
  end # end of filename

else
  p "File Open Error!"
end

http://pastie.org/238588

2008年7月2日 星期三

C# Error CS1501

寫C#的時候發現這個錯誤,原因是我使用了繼承了某個建構子有設定值的類別。

後來在這邊翻到,原來有建構子有設定值傳入的話,要再後面加上: base(Object o)這樣的結構。

這樣的寫法我好像在C++看過,可能是我C++還不夠熟的關係吧 XD

class Base
{
    public Base(string s)
    {
    }
}

class Derived : Base   
{ // CS1501
    public Derived(string s) : base(s)
    {
    }
}

2008年5月19日 星期一

簡易物件繼承

程式目的:利用類別繼承設計一個完整 物件導向c++程式,可以從鍵盤輸入學生 學號
性別,國文,英文,數學 成績,並在檔案輸出每位學生 資料

程式碼:
#include  //基本輸入輸出 
#include  //輸出檔案用 
#include   //處理string用 
using namespace std;

class personal  //個人資料 
{
private :
string name;       //姓名 
string id;         //學號 
char sex;          //性別 
public :
void setpersonal(string n,string i,char s) //設定資料 
{
name = n;
id = i;
sex = s;               
}
string Name() { return name;}
string Id() { return id;}
char Sex() {return sex;}
};
class student : public personal //個人成績 
{
private :
int chinese;   // 中文 
int english;   // 英文 
int math;      // 數學 
public :
void setstudent(string n,string i,char s,int c,int e,int m) //設定資料 
{
chinese = c;
english = e;
math = m;
setpersonal(n,i,s);    
}
int getChinese() { return chinese; }
int getEnglish() { return english; }
int getMath() { return math; }
};

int main() {
student st;
string name,id;
char sex;
int cht,eng,math;
// 使用者輸入資料 
cout << "Name:";
cin >> name;
cout << "ID:";
cin >> id;
cout << "Sex(M/F):";
cin >> sex;
cout << "Chinese:";
cin >> cht;
cout << "English:";
cin >> eng;
cout << "Math:";
cin >> math;
// 建立個人資料 
st.setstudent(name,id,sex,cht,eng,math);
// 輸出至檔案 
ofstream outfile ;
outfile.open("student.txt");
outfile << "Name: " << st.Name() << endl
<< "ID: " << st.Id() << endl
<< "Sex: " << st.Sex() << endl
<< "Chinese: " << st.getChinese() << endl
<< "English: " << st.getEnglish() << endl
<< "Math: " << st.getMath() << endl
;    
system("pause");
return EXIT_SUCCESS;
}

2008年5月10日 星期六

在windows下使用bat和wget抓東西

查了一下語法,發現bat也可以這樣用。但到底為什麼要這樣寫,我還是沒有很懂 @@

程式目的:抓下特定網頁,並且用日期去命名
程式碼:
for /f "tokens=1-5 delims=/ " %%d in ("%date%") do wget http://tw.futures.finance.yahoo.com/future/l/opt_TXO_1.html -O%%d-%%e-%%f.html --wait=10


參考網站:

2008年3月6日 星期四

計算總合

算是寫For的練習,因為在修之前的課,就順便整理一下

計算: 總合=1+2+4+7+11...
#include <iostream>
#include <stdio.h>
using std::cout;
using std::cin;
using std::endl;

main ()
{
long sum=0,num=1;       //設定暫存數字和總合 
long times;             //讀入要跑的次數 
cout << "N=";           //輸出字串 
cin >> times;           //讀入字數 
for (long i=0;i<times;i++)
{
num = i + num;        //1+2+4+7+11...
//  cout << num << "+";   //顯示過程 
sum += num;           //加總 
}
cout << "Sum=" << sum << endl;//印出總合 
system("pause");         //暫停程式 
return 0;
}

http://pastie.caboo.se/170514

2008年1月22日 星期二

Mahjong 麻將遊戲

大學畢業前總是要做一個專題,因此我跟同學就選擇做麻將遊戲。

但是時間總是不夠的,目前只做出了台灣十六張麻將,其他原本預定的日本麻將或是香港麻將,和網路連線功能都還無法實現。

並且我還把程式碼放在Google Code,若之後還有其他有興趣的人可以繼續開發。

PS.當初選C#來寫有點後悔,要跨平台的方法實在是太麻煩了。

Google Code: Mahjong

github: Superbil/Mahjong

現在還在最終測試,不久之後就可以開放測試了。

註:以github的為主,google code那邊會慢慢同步(就是我會忘記啦 XD)