Code Katas existuje veľké množstvo pre rôzne programovacie jazyky (viď napríklad tento zoznam alebo tento web), vo všeobecnosti však nezáleží, v akom jazyku dané cvičenie riešite.
String Calculator
- 1. Create a simple String calculator with a method int Add(string numbers)
- a. The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0) for example “” or “1” or “1,2”
b. Start with the simplest test case of an empty string and move to 1 and two numbers
c. Remember to solve things as simply as possible so that you force yourself to write tests you did not think about
d. Remember to refactor after each passing test
3. Allow the Add method to handle new lines between numbers (instead of commas).- a. the following input is ok: “1\n2,3” (will equal 6)
b. the following input is NOT ok: “1,\n” (not need to prove it - just clarifying)
- a. to change a delimiter, the beginning of the string will contain a separate line that looks like this: “//[delimiter]\n[numbers…]” for example “//;\n1;2” should return three where the default delimiter is ‘;’ .
b. the first line is optional. all existing scenarios should still be supported
- a. The method can take 0, 1 or 2 numbers, and will return their sum (for an empty string it will return 0) for example “” or “1” or “1,2”
Moje riešenie
F#
Kód: Vybrat vše
open System
let MakeList (s:string)=
if (s.StartsWith "//" ) then
let (parts:string array) = Array.ofSeq(s.Split([|'\n'|],2))
let delims = [|parts.[0].Replace("//","")|]
List.ofSeq(parts.[1].Split(delims, StringSplitOptions.None))
else
List.ofSeq(s.Split [|',';'\n'|])
let Add (s:string)=
if (String.IsNullOrEmpty(s)) then 0
else
let numbers = List.map (fun n->int n) (MakeList s)
let negatives = List.filter (fun n -> n < 0) numbers
if (negatives.Length>0) then
failwith ("negatives not allowed "+ (List.reduce (fun acc elem -> acc+","+elem) (List.map (fun n->n.ToString()) negatives)))
else
List.reduce (fun acc elem -> acc + elem) numbers
Kód: Vybrat vše
public IEnumerable MakeList(string s)
{
if (s.StartsWith("//"))
{
var parts = s.Split(new string[]{"\n"},StringSplitOptions.None);
var delims = new string[]{parts[0].Replace("//","")};
return parts[1].Split(delims,StringSplitOptions.None).Select(l=>Int32.Parse(l));
}
return s.Split(new char[]{',','\n'}).Select(l=>Int32.Parse(l));
}
public int Add(string s)
{
if (String.IsNullOrEmpty(s)) return 0;
var numbers = MakeList(s);
var negatives = numbers.Where(l=> l < 0);
if (negatives.Any())
{
throw new ArgumentException("Negatives not allowed "+String.Join(",",negatives.Select(l=>l.ToString()).ToArray()));
}
return numbers.Aggregate(0, (acc,elem) => acc+elem);
}