編碼也快樂:取得3升水C#版

北落師門發表於2013-04-10
private string result = "";     //用來儲存操作過程
protected void Button1_Click(object sender, EventArgs e)
{
    result += "現在有兩個空壺<5升水壺>和<6升水壺>;<br />";  //初始化
    string finaly_result = ChangeWater(0, 0);      //得到結果
    this.ok.InnerHtml = finaly_result;             //輸出到前臺
}

private int LeaveFive = 0;      //<5升水壺>剩餘水量
private int LeaveSix = 0;       //<6升水壺>剩餘水量
private string operate = "";    //記錄操作步驟
private string ChangeWater(int _PortFive, int _PortSix)
{
    if (_PortFive == 3 || _PortSix == 3)    //如果其中有一個水壺水量剩餘量為3升,則終止操作。
    {
        if (_PortFive == 3)
        {
            result += String.Format("現在<5升的水壺>中只有{0}升水了。<br />", _PortFive);
        }
        if (_PortSix == 3)
        {
            result += String.Format("現在<6升的水壺>中只有{0}升水了。<br />", _PortSix);
        }
        return result;
    }
    else
    {

        operate = "";           //將操作步驟清空
        if (_PortFive == 0)     //如果<5升水壺>的水量為0,則將其將滿水。
        {
            operate += "將<5升水壺>灌滿水;<br />";
            LeaveFive = 5;
            _PortFive = 5;
        }
        if (_PortSix == 6)      //如果<6升水壺>的水量滿的話,則將其將清空。
        {
            operate += "將<6升水壺>清空;<br />";
            LeaveSix = 0;
            _PortSix = 0;
        }

        operate += "將<5升水壺>中的水倒入<6升水壺>中,";
        int six_space = 6 - _PortSix;           //計算<6升水壺>的剩餘空間
        LeaveFive = _PortFive - six_space;      //計算執行操作以後<5升水壺>剩下的水量

        if (LeaveFive < 0 || LeaveFive == 0)    //如果<5升水壺>的水量為0或負,則說明<5升水壺>被清空了
        {
            operate += "此時<5升水壺>為空,";
            LeaveFive = 0;
            LeaveSix += _PortFive;
            operate += String.Format("此時<6升水壺>還剩下{0}升;<br />", LeaveSix);

        }
        else
        {
            operate += String.Format("此時<5升水壺>中還剩下{0}升水,", LeaveFive);
            LeaveSix = 6;
            operate += String.Format("此時<6升水壺>中為{0}升;</br>", LeaveSix);
        }
        result += operate;
        ChangeWater(LeaveFive, LeaveSix);       //遞迴執行,直到得到答案為止。

        return result;
    }
} 

相關文章