2012年6月26日 星期二

使用 VirtualBox 代替 Android SDK 的 Emulator

開發一個 Android App 難免需要一個模擬機去測試運作效果

一般來說模擬有三個方法

1. 使用真實 Android 手機測試 (將手機設定為 debug mode用USB線與PC連接)
2. 使用 Android SDK 的 Emulator (跑得很慢)
3. 使用 VirtualBox 代替 Android SDK 的 Emulator (只說 windows下設定)


這裡說的是第三個方法的心得,怎樣設定才最簡單、方便,不是 Step by Step的畫面教學。


1. 在 VirtualBox 中的虛擬機中的 Network Attached to 選用 NAT (轉址方法),在 Port Forward 中,按 "+"號新增一個虛擬機與 HostPC溝通的 Port Forwarding Rules,Rule 1,在 Host Port 輸入 5555,Guest Port 輸入 5555後按OK。

2. 製造一個 ado connect.bat的檔案,輸入以一句的下內容 (以下假設 android-sdk 解壓在 C:\  )

start C:\android-sdk\platform-tools\adb.exe connect localhost

3. 安裝 Escipse並裝上 ADT plugin後,執行 Escipse,不需要在 AVD(Android Virtual Device) Manager中create一個新的 AVD,Run Configuration 中 Target 選 Manual(手動選模擬機)。

4. Escipse 中按 Run 前,double click ado connect.bat 一次,那麼 Escipse 便會認得 Virtualbox 中的虛擬機了,當然同一時間只可以跑一個虛擬機,不要跑多個虛擬機。



註:
adb 全名為 Android Debug Bridge
Android調試橋(ADB)是一種多用途的命令行工具,可以讓你在一個模擬器實例或連接Android的供電設備進行通信,
android-sdk 的 android-sdk\platform-tools\可找到 adb.exe。


延伸閱讀:

使用android x86代替模擬器 step by step

用VirtualBox開啟Android模擬器(Emulator is too slow)

Use adb To Install Google Play Apps To Android 4.0.3 Buildroid In VirtualBox

Introduction of Android Debug Bridge (ADB)

Android模擬器adb命令介紹

ADB經由VirtualBox上的USB Port存取Android硬體





註:

既然是模擬器,那麼打電話,短訊,重力感應,GPS、攝像頭等等功能都不支援,要測試你還是得去弄台真機器調試吧!

2012年6月25日 星期一

轉貼:讓 Eclipse 有類似 intellisense 之自動完成功能

用過 Visual Studio (VS) 的人就會知道 Intellisense 功能有多強大
敲首字便可開始提示,以及大小寫校正,但 Eclipse 預設是沒有開啟這功能的
必須要按 Alt + / 才會出現選單供選擇,對於不習慣按熱鍵的人來說實在是有點不方便

想要開啟如同 VS 首字開始自動提示的功能的話,請照下面步驟

  1. Open Eclipse
  2.  (menu) Windows -> Preferences -> Java -> Editor -> Content Assist
  3.  勾選 Auto-Activation,Auto activation delay 為提示出現的延遲時間,建議可以設為 0
  4.  Auto activation triggers for Java: 原本是 dot 改成 .abcdefghijklmnopqrstuvwxyz(,


現在可以在 Ecplise 中體驗如同 VS 的 Intellisense 功能了

ps. 提示有時可能會有點慢,畢竟是 Java-based 的 IDE,就不要苛求速度了。

延伸閱讀

http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.jdt.doc.user/tips/jdt_tips.html

2012年6月20日 星期三

轉貼:VirtualBox 裝上 Android 4.04 試 Apps

下載 VirtualBox image file

  • vbox86p : Built for a “phone”, 480×800 default resolution
  • vbox86t : Built for a “tablet”, 1024×600 default resolution
  • vbox86tp : Built for a “tablet” with phone capabilities, 1024×600 default resolution

buildroid_vbox86t_4.0.4_r1.1-20120610b_gapps_houdini.ova (which also includes gapps) (ARM libs support, use binary translation)


more refs ...
http://keyable.blogspot.tw/2012/ ... ndroid-404-for.html

如果安裝 image file後,看不見有 Google play (Android market),參考以下面連,自己手動裝上 Google play。

http://keyable.blogspot.hk/2012/ ... -apps-includes.html


詳細安裝介紹 (外接連結)
http://januslin.blog.ithome.com.tw/post/1861/154234





已知問題:
一般情況下 youtube 不能顯示畫面,只有聲音,全螢幕才有畫有聲。



Buildroid VM configuration

既然係 PC 大 Monitor上睇

--> resolution 就改大d,例如 1280 x 800 -16, 1366 x 768 -16

DPI 改 240

keyboard 改 Virtual keyboard with physical hotkeys


另外轉貼 hotkeys:

Quick tips for using the VM:

    if you don’t see the mouse on the Android screen, use the VirtualBox menu to disable mouse integration (Host key + I)
    the “Windows Key” corresponds to the Android Home button
    Esc corresponds to the Android back button
    F2 corresponds to the Android menu button
    F3 corresponds to the Android search button
    Alt+F1 => switch to console mode
    Alt+F7 => switch to GUI mode


另外補充一下虛擬機中主頁、返回、關機、菜單對應的鍵盤按鍵

Home鍵 -> Win鍵
返回鍵 -> ESC鍵
掛機鍵 -> alt+F4
菜單鍵 -> 鍵盤菜單鍵,一般在右邊win鍵和ctrl鍵中間




如果遇到 "處理購買交易時發生錯誤。(DF-BPA-13)"

關於這個狀況,應該是最近play商店更新後出現的bug,建議可以使用以下步驟

到設定 --> 應用程式 --> 全部


1. Google Play商店 -->
-->        強制停止
-->        清除資料

2. Google 服務架構
-->        強制停止
-->        清除資料

3. 重開機就行

2012年6月19日 星期二

以JS code 的OO方法實現樹狀結構

出處:hkepc 討論區原貼

效果


 food
       fruit
          Red
             Cherry
          Yellow
             Banana
       Meat
          Beef
          Pork
 

Tree hierarchy: (在 IE 下不能正常運行)



JS code
<script language="javascript">
<!--

var $ = function(_id) {return document.getElementById(_id);};

function Node(nodeName,nodeParentID, indentNum){
        this.nodeName = nodeName;
        this.nodeParentID = nodeParentID;
        this.childNodes = [];
        this.add=function(node){
                        this.childNodes[this.childNodes.length] = node;
                };
}

function createTree(){
        var dataAry = [
/*0*/                ["root"-1],
/*1*/                ["food",0],
/*2*/                ["fruit",1],
/*3*/                ["Meat",1],
/*4*/                ["Red",2],
/*5*/                ["Yellow",2],
/*6*/                ["Cherry",4],
/*7*/                ["Banana",5],
/*8*/                ["Beef",3],
/*9*/                ["Pork",3]
        ];
        
        var tmpAry=[]; 
        for(var i=0;i<dataAry.length;i++){
                tmpAry[tmpAry.length]= new Node(dataAry[i][0], dataAry[i][1]);
        }

        for(var i=1;i<tmpAry.length;i++){
                var parentIdx = dataAry[i][1];
                tmpAry[parentIdx].add(tmpAry[i]);
        }

        return tmpAry[0];
}

var debugtxt = [];

function debug(msg){
        debugtxt[debugtxt.length] = msg;
}


function walkTree(aTreeNode, indent){
        for(var i=0;i<aTreeNode.childNodes.length;i++){
                debug(indent + aTreeNode.childNodes[i].nodeName + "<br/>");
                
                var subNodes = aTreeNode.childNodes[i].childNodes;                                                                
                if (subNodes.length>0) {
                        walkTree(aTreeNode.childNodes[i], "   " + indent);
                }
        }
}

var treeRoot=null;
function printHierarchy(){
        debugtxt = [];        
        treeRoot = createTree();        
        walkTree(treeRoot, "");

        $("tree1").innerHTML = debugtxt.join("");
}

function clearHierarchy(){
        $("tree1").innerHTML = "";
}
//-->
</script>

html code
Tree hierarchy: <br>
<input type="button" onClick="printHierarchy();" value="Print hierarchy">
<input type="button" onClick="clearHierarchy();" value="Clear data">
<div id="tree1"></div>
延伸閱讀:

google 搜索 樹狀結構
php實現樹狀結構無級分類

最簡單的 jquery 樹狀表單範例


  • 第1章 Javascript簡介
  • 第2章 Javascript基礎
  • 第3章 CSS基礎
    • 第3.1節 CSS的概念
    • 第3.2節 使用CSS控制頁面
      • 3.2.1 行內樣式
      • 3.2.2 內嵌式
    • 第3.3節 CSS選擇器
  • 第4章 CSS進階
    • 第4.1節 div標記與span標記
    • 第4.2節 盒子模型
    • 第4.3節 元素的定位
      • 4.3.1 float定位
      • 4.3.2 position定位
      • 4.3.3 z-index空間位置

js code
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script language="javascript">
$(function(){
 $("li:has(ul)").click(function(e){
  if(this==e.target){
   if($(this).children().is(":hidden")){
    //如果子項是隱藏的則顯示
    $(this).css("list-style-image","url(http://www.matrox.com/graphics/media/image/style/list_minus.gif)")
    .children().show();
   }else{
    //如果子項是顯示的則隱藏
    $(this).css("list-style-image","url(http://www.matrox.com/graphics/media/image/style/list_plus.gif)")
    .children().hide();
   }
  }
  return false; //避免不必要的事件混繞
 }).css("cursor","pointer").click(); //加載時觸發點擊事件
 
 //對於沒有子項的選單,統一設置
 $("li:not(:has(ul))").css({
  "cursor":"default",
  "list-style-image":"none"
 });
});
</script>

html code
<br />
<ul>
<li>第1章 Javascript簡介</li>
<li>第2章 Javascript基礎</li>
<li>第3章 CSS基礎
  <ul>
<li>第3.1節 CSS的概念</li>
<li>第3.2節 使用CSS控制頁面
    <ul>
<li>3.2.1 行內樣式</li>
<li>3.2.2 內嵌式</li>
</ul>
</li>
<li>第3.3節 CSS選擇器</li>
</ul>
</li>
<li>第4章 CSS進階
  <ul>
<li>第4.1節 div標記與span標記</li>
<li>第4.2節 盒子模型</li>
<li>第4.3節 元素的定位
    <ul>
<li>4.3.1 float定位</li>
<li>4.3.2 position定位</li>
<li>4.3.3 z-index空間位置</li>
</ul>
</li>
</ul>
</li>
</ul>

狼、羊、菜威力加強版問題 C++ 解題

題目:

Lulu has to transfer the cabbage, the goat, the wolf, the stick and the fire from one bank of the river to the other bank.
But there are only two seats available on his boat !

Furthermore, if the goat and the cabbage stay together on a bank as Lulu is leaving on his boat, the goat will eat the cabbage.
If the wolf and the goat stay together as Lulu is leaving, the wolf will eat the goat !
If the stick and the wolf stay together as Lulu is leaving, the stick will beat the wolf !
If the fire and the stick stay together as Lulu is leaving, the fire will burn the stick !

Click on the "items" to place them on the boat or on the bank. Click on the arrow to make the boat cross the river.

There are 2 levels in this game.

Good luck !


Play
http://jeux.lulu.pagesperso-orange.fr/html/anglais/loupChe/loupChe2.htm






#include <iostream>
#include <vector>
using namespace std;

const int TARGET_STATE = 63;  // 111 111b

vector<int> crossSnapshot;
vector<int> takerSnapshot;

void showPauseMsg();

enum{
  FARMER=32, // 100000 b
  WOLF=16, // 010000 b
  GOAT = 8, // 001000 b
  CABBAGE=4, // 000100 b
  FIRE = 2,  // 000010 b
  STICK = 1  // 000001 b
};


//toggle the bit N array
//at bankA = 0, at bankB = 1

int cross[] = {
 FARMER,
 FARMER | WOLF,
 FARMER | GOAT,
 FARMER | CABBAGE,
 FARMER | FIRE,
 FARMER | STICK,

 FARMER | WOLF | GOAT,
 FARMER | WOLF | CABBAGE,
 FARMER | WOLF | FIRE,
 FARMER | WOLF | STICK,

 FARMER | GOAT | CABBAGE,
 FARMER | GOAT | FIRE,
 FARMER | GOAT | STICK,

 FARMER | CABBAGE | FIRE,
 FARMER | CABBAGE | STICK,

 FARMER | FIRE | STICK
};

void printState(int iState){
 //print out Bit N, N start from 0

 int N=6;
 for(int i=N-1;i>=0;i--)
 {
  cout << ((iState >> i ) & 1);//show Bit 3
 }
 cout << endl;
}

int farmer(int iState){
 //get a Bit N of iState, N start from 0
 return ((iState >> 5 ) & 1);
}
int wolf(int iState){
 return ((iState >> 4 ) & 1);
}
int goat(int iState){
 return ((iState >> 3 ) & 1);
}
int cabbage(int iState){
 return ((iState >> 2 ) & 1);
}

int fire(int iState){
 return ((iState >> 1 ) & 1);
}

int stick(int iState){
 return ((iState >> 0 ) & 1);
}

bool isSafe(int state){
 if( goat(state) == wolf(state) &&
  goat(state) != farmer(state))
 {
  return false;
 }

 if( goat(state) == cabbage(state) &&
  goat(state)!=farmer(state))
 {
  return false;
 }

 if( stick(state) == wolf(state) &&
  stick(state) != farmer(state))
 {
  return false;
 }

 if( fire(state) == stick(state) &&
  fire(state) != farmer(state))
 {
  return false;
 }

 return true;
}

bool isTry(int state){
 bool isTried = false;

 for(int j=0; j < crossSnapshot.size();j++){
  //printState(crossSnapshot[j]);

  if (state == crossSnapshot[j]){
   isTried = true;
   break;
  }
 }
 return isTried;
}

void printTaker(int i){
 char* msg[] = {
  "farmer goes alone",
  "farmer takes wolf",
  "farmer takes goat",
  "farmer takes cabbage",
  "farmer takes fire",
  "farmer takes stick",

  "farmer takes wolf & goat",
  "farmer takes wolf & cabbage",
  "farmer takes wolf & fire",
  "farmer takes wolf & stick",

  "farmer takes goat & cabbage",
  "farmer takes goat & fire",
  "farmer takes goat & stick",

  "farmer takes cabbage & fire",
  "farmer takes cabbage & stick",

  "farmer takes fire & stick"
 };

 if(i >= 0 && i <= 15) {
  cout << msg[i] << endl;;
 }
}

void printEveryState(vector<int> &crossSnapshot){
 cout << "total number cross state = " << crossSnapshot.size()<<endl;

 for(int j=0; j < crossSnapshot.size();j++){
  printState(crossSnapshot[j]);
 }
}

void printEveryState2(vector<int> &takerSnapshot){
 cout << "The cross step is show as belowing." << endl;

 for(int j=0; j < takerSnapshot.size();j++){
  cout << j+1 << ". ";
  printTaker(takerSnapshot[j]);
 }

 cout <<endl;
}

void recordTriedState(int state, int i, vector<int> &crossSnapshot){
 //save snapshot
 crossSnapshot.push_back(state);
 takerSnapshot.push_back(i);
}

void RollbackRecordState(int state, vector<int> &crossSnapshot){
 //delete previous snapshot
 crossSnapshot.pop_back();
 takerSnapshot.pop_back();
}

void crossRiver(int state, vector<int> &crossSnapshot){
 if (state == TARGET_STATE){
  //printEveryState(crossSnapshot);
  printEveryState2(takerSnapshot);
  //stop recurive iteration

  showPauseMsg();
  exit(0);
  return;
 }

 //for every cross choice
 for(int i=0; i< 15; i++){

  int boat = (crossSnapshot.size()+1) % 2; //0 or 1, 0 at banka, 1 at bankb
  int mover = cross[i];

  if(boat==0)
  {
   if ((state & mover)!= 0){ continue; }
  }
  else
  {
   if ((state & mover)!= mover){ continue; }
  }

  int nextCrossState = state ^ cross[i];

  if(isSafe(nextCrossState) && !isTry(nextCrossState)){
   recordTriedState(nextCrossState, i, crossSnapshot);

   //printTaker(i, state);
   //recurive to call itself
   crossRiver(nextCrossState, crossSnapshot);

   RollbackRecordState(nextCrossState, crossSnapshot);
  }
 }
}

void showPauseMsg(){
    cout << "Press any key to be continue" << endl;
 getchar();
}

int main() {
 int initialState = 0;

 //save first snapshot
 crossSnapshot.push_back(initialState);

 crossRiver(initialState, crossSnapshot);
 showPauseMsg();
 return 0;
}
 
 
Output:

The cross step is show as belowing.
1. farmer takes goat & stick
2. farmer goes alone
3. farmer takes wolf
4. farmer takes wolf & goat
5. farmer takes wolf & cabbage
6. farmer takes wolf
7. farmer takes goat
8. farmer takes goat & stick
9. farmer takes wolf & fire
10. farmer goes alone
11. farmer takes goat & stick

Press any key to be continue

狼、羊、菜問題 C++ 解題

古老的智力遊戲題其實最適合用 functional language 或 logic language 或 AI language (Prolog)去解,但這解題的程式碼是我多年前寫下的,懶得修改,只貼出來留念,有興趣的人可以用更適合 language去解題,程式應該是少很多,而且解題思路會更清晰。

問題:

一個農夫帶著一只狼,一只羊和一籃菜回家,途中要過一條河,唯一的渡河工具是一條小船,因為船真的是太小了,農夫最多只能帶三樣東西的其中一件划船過河;可是,要是農夫不在旁的話,狼會咬羊,羊會吃菜,農夫應怎樣過河才可使得羊和菜都無損呢?



 

#include <iostream>
#include <vector>
using namespace std;

const int TARGET_STATE = 15;  // 1111b

vector<int> crossSnapshot;
vector<int> takerSnapshot;

enum{
  FARMER=8, // 1000 b
  WOLF=4, // 0100 b
  GOAT = 2, // 0010 b
  CABBAGE=1 // 0001 b
};


//toggle the bit N array
//at bankA = 0, at bankB = 1

int cross[] = {
 FARMER, //FARMER  //1000b, 8, Farmer at bankB
 FARMER | WOLF, //FARMER, WOLF //1100b, 12
 FARMER | GOAT, //FARMER, GOAT //1010b, 10
 FARMER | CABBAGE //FARMER,CABBAGE //1001b, 9
};

void printState(int iState){
 //print out Bit N, N start from 0

 int N=4;
 for(int i=N-1;i>=0;i--)
 {
  cout << ((iState >> i ) & 1);//show Bit 3
 }
 cout << endl;
}


int farmer(int iState){
 //get a Bit N of iState, N start from 0
 return ((iState >> 3 ) & 1);
}
int wolf(int iState){
 return ((iState >> 2 ) & 1);
}
int goat(int iState){
 return ((iState >> 1 ) & 1);
}
int cabbage(int iState){
 return ((iState >> 0 ) & 1);
}

bool isSafe(int state){
 if( goat(state) == wolf(state) &&
  goat(state) != farmer(state))
 {
  return false;
 }

 if( goat(state) == cabbage(state) &&
  goat(state)!=farmer(state))
 {
  return false;
 }

 return true;
}

bool isTry(int state){
 bool isTried = false;

 for(int j=0; j < crossSnapshot.size();j++){
  //printState(crossSnapshot[j]);

  if (state == crossSnapshot[j]){
   isTried = true;
   break;
  }
 }
 return isTried;
}


void printTaker2(int i){
 char* msg[] = {
  "farmer goes alone",
  "farmer takes wolf",
  "farmer takes goat",
  "farmer takes cabbage"
 };

 if(i >= 0 && i <= 3) {
  cout << msg[i] << endl;;
 }
}

void printEveryState(vector<int> &crossSnapshot){
 cout << "total number cross state = " << crossSnapshot.size()<<endl;

 for(int j=0; j < crossSnapshot.size();j++){
  printState(crossSnapshot[j]);
  //printTaker2(crossSnapshot[j]);
 }
}

void printEveryState2(vector<int> &takerSnapshot){
 cout << "The cross step is show as belowing." << endl;

 for(int j=0; j < takerSnapshot.size();j++){
  cout << j+1 << ". ";
  printTaker2(takerSnapshot[j]);
 }

 cout <<endl;
}

void recordTriedState(int state, int i, vector<int> &crossSnapshot){
 //save snapshot
 crossSnapshot.push_back(state);
 takerSnapshot.push_back(i);
}

void RollbackRecordState(int state, vector<int> &crossSnapshot){
 //delete previous snapshot
 crossSnapshot.pop_back();
 takerSnapshot.pop_back();
}

void crossRiver(int state, vector<int> &crossSnapshot){
 if (state == TARGET_STATE){
  //printEveryState(crossSnapshot);
  printEveryState2(takerSnapshot);
  //stop recurive iteration
  return;
 }

 //for every cross choice
 for(int i=0; i<4; i++){
  int nextCrossState = state ^ cross[i]; // use bitwise^ to toggle the Bit i

  if(isSafe(nextCrossState) && !isTry(nextCrossState)){
   recordTriedState(nextCrossState, i, crossSnapshot);

   //printTaker(i, state);
   //recurive to call itself
   crossRiver(nextCrossState, crossSnapshot);

   RollbackRecordState(nextCrossState, crossSnapshot);
  }
 }
}

int main() {
 int initialState = 0;

 //save first snapshot
 crossSnapshot.push_back(initialState);

 crossRiver(initialState, crossSnapshot);

    cout << "Press any key to be continue" << endl;
 getchar();
 return 0;
} 


Output:

The cross step is show as belowing.
1. farmer takes goat
2. farmer goes alone
3. farmer takes wolf
4. farmer takes goat
5. farmer takes cabbage
6. farmer goes alone
7. farmer takes goat

The cross step is show as belowing.
1. farmer takes goat
2. farmer goes alone
3. farmer takes cabbage
4. farmer takes goat
5. farmer takes wolf
6. farmer goes alone
7. farmer takes goat

Press any key to be continue

 
延伸閱讀:

狐狸、鵝、豆子問題 - 維基百科,自由的百科全書

http://en.wikipedia.org/wiki/Fox,_goose_and_bag_of_beans_puzzle

 數學遊戲與欣賞 - 過河問題

渡河問題 - 维基百科,自由的百科全书


過河問題的圖論解法 - 那個誰 - CSDNBlog

黑夜過橋 C++ 解題



    請幫助一家五口在黑夜中過河。

    注意事項:

    1.因為是黑夜,他們必須帶備燈。
    2.每位家庭成員都有不同的速度過橋,由1秒、3秒、6秒、8秒、到12秒。
    3.橋只可最多承受2人的重量。
    4.當2人同時在橋上行走,速度必跟隨較慢的一位。
    5.燈只足夠維持30秒。


#include <iostream>
#include <string>
#include <vector>

using namespace std;

const int TARGET_STATE = 64-1;  //  111 111b

vector<int> crossSnapshot;
vector<int> takerSnapshot;

void showPauseMsg();

enum{
 lamp=32,
 m12=16,
 m8=8,
 m6=4,
 m3=2,
 m1=1
};

int cross[] = {
 m12, m8, m6, m3, m1,
 m12|m8, m12|m6, m12|m3, m12|m1,
 m8|m6, m8|m3, m8|m1,
 m6|m3, m6|m1,
 m3|m1
};

int crossCost[]={
 12, 8, 6, 3, 1,
 12, 12, 12, 12,
 8,8,8,
 6,6,
 3
};

int crossUppIdx = (sizeof(cross)/ sizeof(int))-1;

void printState(int iState){
 //print out Bit N, N start from 0

 int N=8;
 for(int i=N-1;i>=0;i--)
 {
  cout << ((iState >> i ) & 1);//show Bit 3
 }
 cout << endl;
}

//get a binary digit N of iNumber, N start from Right to Left
// Rightmost is 1
//return 0 or 1, Bit N at iNumber

int getBitN(int iNumber, int N){
 return (iNumber >> (N-1)) & 1;
}

int getLampState (int iState){ return getBitN(iState, 6);}

bool isSafe(vector<int> &takerSnapshot, int addCost){
 int sum =0;

 for(int j=0; j<takerSnapshot.size();j++){
  sum += crossCost[takerSnapshot[j]];
 }

 sum += addCost;

 if (sum >30){ return false;}

 return true;
}

bool isTry(int state){
 bool isTried = false;

 for(int j=0; j < crossSnapshot.size();j++){
  if (state == crossSnapshot[j]){
   isTried = true;
   break;
  }
 }
 return isTried;
}

void printTaker(int i){
 char* msg[] = {
  "12", "8", "6", "3", "1",
  "(12,8)", "(12,6)", "(12,3)", "(12,1)",
  "(8,6)", "(8,3)", "(8,1)",
  "(6,3)", "(6,1)",
  "(3,1)"
 };

 if(i >= 0 && i <= crossUppIdx) {
  cout << msg[i] << endl;
 }
}

string getTaker(int i){
 char* msg[] = {
  "12", "8", "6", "3", "1",
  "(12,8)", "(12,6)", "(12,3)", "(12,1)",
  "(8,6)", "(8,3)", "(8,1)",
  "(6,3)", "(6,1)",
  "(3,1)"
 };

 if(i >= 0 && i <= crossUppIdx) {
  return string(msg[i]);
 }

 return string("");
}

void printEveryBitState(vector<int> &crossSnapshot){
 cout << "total number cross state = " << crossSnapshot.size()<<endl;

 for(int j=0; j < crossSnapshot.size();j++){
  printState(crossSnapshot[j]);
 }
}

void printEveryWordState(vector<int> &takerSnapshot){
 cout << "The cross step is show as belowing." << endl;

 for(int j=0; j < takerSnapshot.size();j++){
  cout << j+1 << ". ";
  cout << getTaker(takerSnapshot[j]);

  if (j%2 == 0){
   cout << " <---" << endl;
  } else {
   cout << " --->"<< endl;
  }
 }
 //add a dummy blank line
 cout <<endl;
}

void printTotalMins(vector<int> &takerSnapshot){
 int totalMins = 0;

 for(int j=0; j < takerSnapshot.size();j++){
  totalMins += crossCost[takerSnapshot[j]];
 }

 cout << "total mins used = " << totalMins << endl;
}

void recordTriedState(int state, int i, vector<int> &crossSnapshot){
 //save snapshot
 crossSnapshot.push_back(state);
 takerSnapshot.push_back(i);
}

void RollbackRecordState(int state, vector<int> &crossSnapshot){
 //delete previous snapshot

 //cout << "roll back ...." << endl << endl;
 //printEveryWordState(takerSnapshot);
 //printEveryBitState(crossSnapshot);

 crossSnapshot.pop_back();
 takerSnapshot.pop_back();
}

bool isMoverSameSideWithBoat(int currentState, int mover){
 bool rv = false;
 int lampState = getLampState(currentState);

 if(lampState==0)
 {
  if ((currentState & mover) == 0){ rv = true; }
 }
 else
 {
  if ((currentState & mover)== mover){ rv = true;  }
 }

 return rv;
}

void crossRiver(int state,
    vector<int> &crossSnapshot)
{
 if (state == TARGET_STATE){
  //printEveryBitState(crossSnapshot);
  printEveryWordState(takerSnapshot);
  printTotalMins(takerSnapshot);

  //stop recurive iteration
  showPauseMsg(); // if u want to print similarly answer, hide this code
  exit(0);  // if u want to print similarly answer, hide this code
  return;
 }

 //for every cross choice
 for(int i=0; i<=crossUppIdx; i++){
  int mover = cross[i];

  bool isMoverSameWithBoat = isMoverSameSideWithBoat(state, mover);

  // if mover object is not same side as boat
  if (!isMoverSameWithBoat){
   continue;
  }

  int nextCrossState = (state ^ mover) ^ lamp; // use bitwise^ to toggle the Bit i

  bool isSafed = isSafe(takerSnapshot, crossCost[i]);

  bool isNotTry = (!isTry(nextCrossState));

  if( isSafed && isNotTry ){
   //printState(nextCrossState);
   //printTaker(i);

   //int x = takerSnapshot.size();
   recordTriedState(nextCrossState, i, crossSnapshot);
   //recurive to call itself
   crossRiver(nextCrossState, crossSnapshot);

   RollbackRecordState(nextCrossState, crossSnapshot);
  }
 }
}

void showPauseMsg(){
    cout << "Press any key to be continue" << endl;
 getchar();
}

int main() {
 //save first snapshot
 crossSnapshot.push_back(0);

 crossRiver(0, crossSnapshot);

 //showPauseMsg();
 return 0;
}


The cross step is show as belowing.
1. (6,1) <---
2. 1 --->
3. (3,1) <---
4. 3 --->
5. (12,8) <---
6. 1 --->
7. (3,1) <---

total mins used = 29
Press any key to be continue

延伸閱讀:

其他人的文章,如果是 N個人一共只帶了一只手電筒等變形問題的版本
http://blog.csdn.net/wuzhekai1985/article/details/6846934

http://renren.it/a/bianchengyuyan/_NET/20111006/133147.html


黑夜過橋問題是可遞迴解的

一家六口過河問題 C++解題

一家六口過河問題 C++解題 出處不知,有多個變化身份的版本

版本1

一家庭欲過河.成員為:爸爸.媽媽.哥哥.姊姊.弟弟.妹妹.僕人.與一隻狗...
過河條件如下:
1.僅有一條小船可供渡河.每次最多搭乘2人(含駕駛)..且僅有爸爸.媽媽.僕人這3人會駕船..
2.爸爸不在兄弟身邊時.媽媽會打兄弟..
3.媽媽不在姊妹身邊時.爸爸會打姊妹..
4.僕人不在狗身邊時.狗會咬其他人..
請問這家人要如何平安過河?


版本2:


http://res.hkedcity.net/general/0001/51/31/riverIQGame.swf



全家人一起到郊外野餐,原本是歡樂的氣氛,卻碰到了逃獄的囚犯的襲擊,所幸逮捕他的警察也即時趕到,全家人因此暫時沒有危險了...;在警察一邊要保護全家人,一邊要看緊囚犯的路上,來到了一個需要過河的地方,但是只有一艘只能同時在兩人的小船,爸爸、媽媽、兩個兒子與兩個女兒,加上一名囚犯與一名警察這8個人該如何順利過河呢?


操作說明:

用滑鼠點選要乘船的人,在點選紅色拉桿,就可以過河。 注意,這家人有點...奇怪:

1.爸爸不可以在沒有媽媽的情況下跟女兒在一起,女兒會被責罵。

2.媽媽不可以在沒有爸爸的情況下跟兒子在一起,兒子會被修理。

3.囚犯不可以在沒有警察的情況下跟其他人在一起,囚犯會傷害他人。


這個版本被人用 flash 製造出來,有良好互動效果,所以就用這個題目做練習吧!

其他類似版本 iPad, iPhone

link


#include <iostream>
#include <string>
#include <vector>

using namespace std;

const int TARGET_STATE = 512-1;  // 1 1111 1111b

vector<int> crossSnapshot;
vector<string> takerSnapshot;

void showPauseMsg();

enum{
 Boat=256,
 Father=128,
 Mather=64,
 Police=32,
 Thief=16,

 Boy1=8,
 Boy2=4,
 Girl1=2,
 Girl2=1
};


int cross[] = {
 Father,//0
 Mather,
 Police,
 Father|Mather,
 Father|Police,
 Father|Boy1,
 Father|Boy2,

 Mather|Police,
 Mather|Girl1,
 Mather|Girl2,

 Police|Thief,
 Police|Boy1,
 Police|Boy2,
 Police|Girl1,
 Police|Girl2
};
int crossUppIdx = 14;

void printState(int iState){
 //print out Bit N, N start from 0

 int N=8;
 for(int i=N-1;i>=0;i--)
 {
  cout << ((iState >> i ) & 1);//show Bit 3
 }
 cout << endl;
}

//get a binary digit N of iNumber, N start from Right to Left
// Rightmost is 1
//return 0 or 1, Bit N at iNumber

int getBitN(int iNumber, int N){
 return (iNumber >> (N-1)) & 1;
}

int getBoatState (int iState){ return getBitN(iState, 9);}

int father (int iState){ return getBitN(iState, 8);}
int mother (int iState){ return getBitN(iState, 7);}
int police (int iState){ return getBitN(iState, 6);}
int thief  (int iState){ return getBitN(iState, 5);}
int boy1 (int iState){ return getBitN(iState, 4);}
int boy2(int iState){ return getBitN(iState, 3);}
int girl1(int iState){ return getBitN(iState, 2);}
int girl2(int iState){ return getBitN(iState, 1);}


bool isSafe(int state){
 if( police(state) != thief(state)
  && (thief(state) == father(state) ||
   thief(state) == mother(state) ||
   thief(state) == boy1(state) ||
   thief(state) == boy2(state) ||
   thief(state) == girl1(state) ||
   thief(state) == girl2(state))
  )
 {
  return false;
 }

 if( father(state)!= mother(state) &&
  (father(state) == girl1(state) ||
   father(state) == girl2(state))
  )
 {
  return false;
 }

 if( mother(state)!= father(state) &&
  (mother(state) == boy1(state) ||
   mother(state) == boy2(state))
  )
 {
  return false;
 }
 return true;
}

bool isTry(int state){
 bool isTried = false;

 for(int j=0; j < crossSnapshot.size();j++){
  //printState(crossSnapshot[j]);

  if (state == crossSnapshot[j]){
   isTried = true;
   break;
  }
 }
 return isTried;
}

void printTaker(int i){
 char* msg[] = {
  "father, _____",
  "mother, _____",
  "police, _____",

  "father, mother",
  "father, police",

  "father, boy1",
  "father, boy2",

  "mother, police",
  "mother, girl1",
  "mother, girl2",

  "police, thief",
  "police, boy1",
  "police, boy2",
  "police, girl1",
  "police, girl2"
 };

 if(i >= 0 && i <= crossUppIdx) {
  cout << msg[i] << endl;
 }
}


string getTaker(int i){
 char* msg[] = {
  "father, _____",
  "mother, _____",
  "police, _____",

  "father, mother",
  "father, police",

  "father, boy1",
  "father, boy2",

  "mother, police",
  "mother, girl1",
  "mother, girl2",

  "police, thief",
  "police, boy1",
  "police, boy2",
  "police, girl1",
  "police, girl2"
 };

 if(i >= 0 && i <= crossUppIdx) {
  return string(msg[i]);
 }

 return string("");
}

void printEveryBitState(vector<int> &crossSnapshot){
 cout << "total number cross state = " << crossSnapshot.size()<<endl;

 for(int j=0; j < crossSnapshot.size();j++){
  printState(crossSnapshot[j]);
 }
}

void printEveryWordState(vector<string> &takerSnapshot){
 cout << "The cross step is show as belowing." << endl;

 for(int j=0; j < takerSnapshot.size();j++){
  cout << j+1 << ". ";
  cout << takerSnapshot[j];

  if (j%2 == 0){
   cout << " --->" << endl;
  } else {
   cout << " <---"<< endl;
  }
 }
 //add a dummy blank line
 cout <<endl;
}

void recordTriedState(int state, int i, vector<int> &crossSnapshot){
 //save snapshot
 crossSnapshot.push_back(state);
 takerSnapshot.push_back(getTaker(i));
}

void RollbackRecordState(int state, vector<int> &crossSnapshot){
 //delete previous snapshot

 //cout << "roll back ...." << endl << endl;
 //printEveryWordState(takerSnapshot);
 //printEveryBitState(crossSnapshot);

 crossSnapshot.pop_back();
 takerSnapshot.pop_back();
}

bool isMoverSameSideWithBoat(int currentState, int mover){
 bool rv = false;
 int boat = getBoatState(currentState);

 if(boat==0)
 {
  if ((currentState & mover) == 0){ rv = true; }
 }
 else
 {
  if ((currentState & mover)== mover){ rv = true;  }
 }

 return rv;
}

void crossRiver(int state, vector<int> &crossSnapshot){
 if (state == TARGET_STATE){
  //printEveryBitState(crossSnapshot);
  printEveryWordState(takerSnapshot);
  //stop recurive iteration

  showPauseMsg(); // if u want to print similarly answer, hide this code
  exit(0);  // if u want to print similarly answer, hide this code
  return;
 }

 //for every cross choice
 for(int i=0; i<=crossUppIdx; i++){
  int mover = cross[i];

  bool isMoverSameWithBoat = isMoverSameSideWithBoat(state, mover);

  // if mover object is not same side as boat
  if (!isMoverSameWithBoat){
   continue;
  }

  int nextCrossState = (state ^ mover) ^ Boat; // use bitwise^ to toggle the Bit i

  bool isSafed = isSafe(nextCrossState);
  bool isNotTry = (!isTry(nextCrossState));

  if( isSafed && isNotTry ){
   //printState(nextCrossState);
   //printTaker(i);

   //int x = takerSnapshot.size();
   recordTriedState(nextCrossState, i, crossSnapshot);
   //recurive to call itself
   crossRiver(nextCrossState, crossSnapshot);

   RollbackRecordState(nextCrossState, crossSnapshot);
  }
 }
}

void showPauseMsg(){
    cout << "Press any key to be continue" << endl;
 getchar();
}

int main() {
 int initialState = 0;

 //save first snapshot
 crossSnapshot.push_back(initialState);
 crossRiver(initialState, crossSnapshot);

 //showPauseMsg();
 return 0;
}


Output: 結果



The cross step is show as belowing.

1. police, thief --->
2. police, _____ <---
3. police, boy1 --->
4. police, thief <---
5. father, boy2 --->
6. father, _____ <---
7. father, mother --->
8. mother, _____ <---
9. police, thief --->
10. father, _____ <---
11. father, mother --->
12. mother, _____ <---
13. mother, girl1 --->
14. police, thief <---
15. police, girl2 --->
16. police, _____ <---
17. police, thief --->

Press any key to be continue


-------------------------------------------------

DOS/capture screen output to a file

click the control menu button on a command window (you can find this button on the left upper corner). Or press Alt + space_bar.

Once the control menu opens, select Edit. From there you can Select All, Mark, or Copy the text you require from the command window.

This text is then copied to the standard Windows clipboard. From there you can paste it in another Windows program.

2012年6月6日 星期三

在 Blogger 使用syntaxhighlighter 3.0

Demo
/**
 * SyntaxHighlighter
 */
public class HelloWorld {

 private static String text = "Hello World!"; 
 
 // Test
 public static void main(String[] arg){
  System.out.println(" - " + text + " - ");
 }
}
步驟1. 登入您的 Blogger。
步驟2. 點選[版面配置]\[範本]\[修改 HTML]。
步驟3. 請以下的範例,複製到 標籤的前面。
<!-- SyntaxHighlighter 3.0.83-->
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shAutoloader.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushAS3.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushColdFusion.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDelphi.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDiff.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushErlang.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushGroovy.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJavaFX.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPowerShell.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushScala.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
步驟4. 找尋 "< / body>"標籤,並在標籤前加入以下字串
    <!-- SyntaxHighlighter 3.0.83-->
    <script type='text/javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all()
    </script>
步驟5. 進入文章編輯,並切換為"修改HTML"模式
下面方法在加入字串時,特殊符號 "<" 、 ">" 需先轉換好,否則會出現HTML
    <pre class="brush: java">
    ...
    // 程式碼
    ...
    </pre>
SyntaxHighlighter uses separate syntax files called brushes to define its highlighting functionality.

Brush nameBrush aliasesFile name
ActionScript3as3, actionscript3shBrushAS3.js
Bash/shellbash, shellshBrushBash.js
ColdFusioncf, coldfusionshBrushColdFusion.js
C#c-sharp, csharpshBrushCSharp.js
C++cpp, cshBrushCpp.js
CSScssshBrushCss.js
Delphidelphi, pas, pascalshBrushDelphi.js
Diffdiff, patchshBrushDiff.js
Erlangerl, erlangshBrushErlang.js
GroovygroovyshBrushGroovy.js
JavaScriptjs, jscript, javascriptshBrushJScript.js
JavajavashBrushJava.js
JavaFXjfx, javafxshBrushJavaFX.js
Perlperl, plshBrushPerl.js
PHPphpshBrushPhp.js
Plain Textplain, textshBrushPlain.js
PowerShellps, powershellshBrushPowerShell.js
Pythonpy, pythonshBrushPython.js
Rubyrails, ror, rubyshBrushRuby.js
ScalascalashBrushScala.js
SQLsqlshBrushSql.js
Visual Basicvb, vbnetshBrushVb.js
XMLxml, xhtml, xslt, html, xhtmlshBrushXml.js

2012年6月5日 星期二

四層動態連動下拉選單例子




Path:

三層動態連動下拉選單例子