diff --git a/.gitignore b/.gitignore index 259148fa..3e94e61a 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,9 @@ *.exe *.out *.app + +# Build dirs +build-* + +# .user files +*.user \ No newline at end of file diff --git a/tdd_intro/homework/02_ternary_numbers/test.cpp b/tdd_intro/homework/02_ternary_numbers/test.cpp index 17503028..58765ef6 100644 --- a/tdd_intro/homework/02_ternary_numbers/test.cpp +++ b/tdd_intro/homework/02_ternary_numbers/test.cpp @@ -16,3 +16,67 @@ The last place in a ternary number is the 1's place. The second to last is the 3 If your language provides a method in the standard library to perform the conversion, pretend it doesn't exist and implement it yourself. */ + +int CharToInt(char c) +{ + return c - '0'; +} + +int Power(int number, int index) +{ + int result = 1; + for (int i = 0; i < index; i++) + { + result *= number; + } + return result; +} +std::vector ParseDigits(const std::string& number) +{ + std::vector result; + for (char ch : number) + { + result.push_back(CharToInt(ch)); + } + return result; +} +int TerToDec(const std::string& ternary) +{ + int result = 0; + std::vector digits = ParseDigits(ternary); + size_t i = 0; + for (auto digit = digits.rbegin(); digit != digits.rend(); ++digit) + { + result += *digit * Power(3, i); + i++; + } + return result; +} + +TEST(PowerTest, ItReturnsNumberMultipliedByNumberNTimesForIndexN) +{ + EXPECT_EQ(5, Power(5, 1)); + EXPECT_EQ(25, Power(5, 2)); + EXPECT_EQ(625, Power(5, 4)); +} +TEST(ParseDigitsTest, ItReturnsVectorWithDigitsForMultipleDigits) +{ + EXPECT_EQ(std::vector({ 1 }), ParseDigits("1")); + EXPECT_EQ(std::vector({ 1, 2, 3 }), ParseDigits("123")); + EXPECT_EQ(std::vector({ 1, 2, 3, 1 }), ParseDigits("1231")); +} + +TEST(TerToDecTest, ItReturnsZeroForZero) +{ + EXPECT_EQ(0, TerToDec("0")); +} +TEST(TerToDecTest, ItReturnsDecRepresentationForAnyNumber) +{ + EXPECT_EQ(1, TerToDec("1")); + EXPECT_EQ(4, TerToDec("11")); + EXPECT_EQ(13, TerToDec("111")); +} +TEST(TerToDecTest, Acceptance) +{ + EXPECT_EQ(302, TerToDec("102012")); +}