Kata Practice C# - DNA to RNA Conversion

Kata Practice C# - DNA to RNA Conversion

這個系列會把自己練習過的 Kata 題目記錄下來,希望除了記錄的性質以外也能夠觀察自己撰寫程式邏輯的進化過程。如果有幸看到這邊的話也可以參考一下,再到 Codewars 的網站註冊一個帳號試著玩看看,自己蠻喜歡整個網站的得分和排行榜設定,會讓人越寫越有成就感喔!

題目

Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. It is composed of four nucleic acid bases Guanine (‘G’), Cytosine (‘C’), Adenine (‘A’), and Thymine (‘T’).

Ribonucleic acid, RNA, is the primary messenger molecule in cells. RNA differs slightly from DNA its chemical structure and contains no Thymine. In RNA Thymine is replaced by another nucleic acid Uracil (‘U’).

Create a function which translates a given DNA string into RNA.

For example:

“GCAT” => “GCAU”
The input string can be of arbitrary length - in particular, it may be empty. All input is guaranteed to be valid, i.e. each input string will only ever consist of ‘G’, ‘C’, ‘A’ and/or ‘T’.

自己的解法

1
2
3
4
5
6
7
8
9
namespace Converter {
public class Converter
{
public string dnaToRna(string dna)
{
return dna.Replace('T','U');
}
}
}

解題脈絡

按照問題的敘述先去 Google 找 C# 有沒有相對應的方法?於是就找到了 Replace 的這個方法,不過感覺這樣只是解決了基本的需求。當然這樣還是有符合題目的需求,但感覺應該還有更符合日常開發的狀況,所以就看了其他人的 Solution。

其他人的解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace Converter {
public class Converter
{
public string dnaToRna(string dna)
{
char[] dnaLetters = new char[4]{'G','C','A','T'};
string upperCaseDna = dna.ToUpper();
if(upperCaseDna.Any( letter => !dnaLetters.Contains(letter)))
throw new ArgumentException();

return upperCaseDna.Replace('T','U');
}
}
}

選擇這個解法的原因

雖然直接使用 Replace 可以完成需求,不過參考的這個 Solution 有將每一步的邏輯都整理起來,即便相較原本的寫法多了一些變數和判斷,但是這樣確有助於釐清整個程式碼的可讀性。即便不需要註解也可以知道這個 Class 在解決的問題是什麼?

觀念釐清

希望之後自己在練習 kata 的時候也能夠想到比較全面的練習,不僅僅是只符合題目的需求而已。

那我們下次見ʘ‿ʘ

評論