iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 15
0
自我挑戰組

TDD - 紅燈,綠燈,重構,30天 TDD之路有你有我系列 第 15

Day15. 你最大,你最小啦!-Codewars_Highest and Lowest

嗨,新年快樂各位,今天新年第一天,還是要寫一下文章啦XDD

今天的題目長這樣

https://ithelp.ithome.com.tw/upload/images/20180101/20107209ccVv0WTOUQ.png

今天題目是要找出字串中的最大的數字和最小的數字,然後先印最大的,在印最小的。
不需要驗證他是不是Int32
他一定有1個數字在輸入中
輸出一定要是兩個數字,先輸出最大的那個。

現在就來拆一下題目吧。

  1. 輸入字串轉換成數字陣列
  2. 找出最大的數字方法
  3. 找出最小的數字方法

首先來吧! Test Code!!!

既然是要先印出最大的數字,那就先從找出最大數字來寫測試案例吧!

[TestMethod]
public void Input_1_Should_Be_1()
{
    Assert.AreEqual("1",Kata.FindHigh("1"));
}

而Production Code 也就是老樣子會長成這個樣子

public static string FindHigh(string s)
{
    throw new System.NotImplementedException();
}

老樣子,跑個測試,沒過很正常,commit一下

https://ithelp.ithome.com.tw/upload/images/20180101/20107209Vo0e0k27du.png

接下來把Production Code改一下,用最簡單的方式解決他!

public static string FindHigh(string s)
{
    return s;
}

接下來跑個測試,PASS!

https://ithelp.ithome.com.tw/upload/images/20180101/20107209Q3LzBwdMXL.png

接下來寫一個測試在兩個數字中找出最大的並輸出吧!

[TestMethod]
public void Input_12_Should_Be_2()
{
    Assert.AreEqual("2",Kata.FindHigh("1 2"));
}

接下來跑一下測試吧,紅燈! Commit!

https://ithelp.ithome.com.tw/upload/images/20180101/20107209BAiReQXXO0.png

接下來再把Production Code改一下

public static string FindHigh(string s)
{
    var sArray = s.Split(' ');
    return sArray.Max();
}

寫完就來跑個測試,PASS,Commit一下唄!

https://ithelp.ithome.com.tw/upload/images/20180101/20107209nDsfhnmv5C.png

接下來重構一下FindHigh這個方法

public static string FindHigh(string s)
{
    return s.Split(' ').Max();
}

FindHigh的方法完成了,就來寫Lowest的測試吧!
在之前先把先前寫的測試前面加上方法名稱,好讓我們分辨。

 [TestMethod]
public void FindLowest_Input_12_Should_Be_1()
{
    Assert.AreEqual("1",Kata.FindLow("1 2"));
}

有了FindHigh這個前車之鑑,所以FindLow很快地就可以通過測試。
接下來把兩個放在一起做最後的輸出吧!
搞了一般的輸入測試之後,發現前面並沒有考慮到負號的數字,所以上面的findHigh跟FindLow都會出錯。

所以需要將兩個方法改成這個樣子。

public static string FindHigh(string s)
{
    return Array.ConvertAll(s.Split(), Convert.ToInt32).Max().ToString();
}

public static string FindLow(string s)
{
    return Array.ConvertAll(s.Split(), Convert.ToInt32).Min().ToString();
}

接下來就多寫幾個測試案例,跑個測試,Pass,Commit!

https://ithelp.ithome.com.tw/upload/images/20180101/201072093y0XedcB4J.png

然後再Codewars上提交! Pass!!

https://ithelp.ithome.com.tw/upload/images/20180101/20107209z9vDSgnCJz.png

通過! PASS!
老樣子我最喜歡的部分就是去看看別人寫這題寫得怎麼樣勒
今天基本上大家都跟我寫得差不多,只是我的有把找出最大跟找出最小的方法拆解出來。
所以我就不把它貼出來了XD

Git url :
https://github.com/SQZ777/Codewars_HightAndLowest

下一題,明天見!


上一篇
Day14. 嘗試切他中路!-Codewars_GetThe Middle Character
下一篇
Day16. 你484正方形?-Codewars_You’re Squre!
系列文
TDD - 紅燈,綠燈,重構,30天 TDD之路有你有我30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言