Created
July 18, 2023 05:43
-
-
Save yuchdev/a26438a6b9e4a434e608cea2c35cc7d7 to your computer and use it in GitHub Desktop.
Exclusive product, little test assignment on C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <numeric> | |
#include <vector> | |
/// @brief: Calculates array of same size, where each element is the product | |
/// of all elements excluding corresponding by index | |
/// Algorithm: O(n) time, O(n) space | |
/// @param: array of int | |
/// @return: array of same size | |
/// @example: {1,2,3,4} => {24, 12, 8, 6}, {1, 2, 3, 4, 5} => {120, 60, 40, 30, 24} | |
auto exclusive_product(const std::vector<int>& input_data) -> std::vector<int> | |
{ | |
int product = std::accumulate(std::begin(input_data), std::end(input_data), 1, std::multiplies<int>()); | |
std::vector<int> result; | |
result.reserve(input_data.size()); | |
for (auto i : input_data) { | |
if (i == 0) { | |
result.push_back(0); | |
} | |
else { | |
result.push_back(product / i); | |
} | |
} | |
return std::move(result); | |
} | |
/// @brief: Check if the result of `exclusive_product()` is correct | |
/// @param input_data: array of int | |
/// @param expected_data: what we expect to get from `exclusive_product()` | |
/// @return: true if result is correct, false otherwise | |
bool sum_product_test(const std::vector<int>& input_data, const std::vector<int>& expected_data) | |
{ | |
auto output_data = exclusive_product(input_data); | |
return output_data == expected_data; | |
} | |
/// @brief: test function | |
void test_cases() | |
{ | |
static const std::vector<std::vector<int>> input_cases { | |
{1, 2, 3, 4}, | |
{0, 0, 0, 0}, | |
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, | |
{} | |
}; | |
static const std::vector<std::vector<int>> expected_cases { | |
{24, 12, 8, 6}, | |
{0, 0, 0, 0}, | |
{3628800, 1814400, 1209600, 907200, 725760, 604800, 518400, 453600, 403200, 362880}, | |
{} | |
}; | |
for (auto i = 0; i < input_cases.size(); ++i) { | |
if (sum_product_test(input_cases[i], expected_cases[i])) { | |
std::cout << "Test " << i << " passed" << std::endl; | |
} | |
else { | |
std::cout << "Test " << i << " failed" << std::endl; | |
} | |
} | |
} | |
auto main() -> int | |
{ | |
std::cout << "Test assignment application\n"; | |
test_cases(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment