Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Create a operate that returns the sum of the 2 lowest constructive numbers given an array of minimal 4 constructive integers. No floats or non-positive integers shall be handed.
For instance, when an array is handed like [19, 5, 42, 2, 77]
, the output needs to be 7
.
[10, 343445353, 3453445, 3453545353453]
ought to return 3453455
.
Possibility 1:
#embody <algorithm>
#embody <vector>
lengthy sumTwoSmallestNumbers(std::vector<int> numbers) {
std::kind(numbers.start(), numbers.finish());
return (lengthy)numbers[0] + (lengthy)numbers[1];
}
Possibility 2:
#embody <algorithm>
unsigned int sumTwoSmallestNumbers(std::vector<int> numbers) {
std::nth_element(start(numbers), subsequent(start(numbers)), finish(numbers));
return (unsigned int)(numbers[0] + numbers[1]);
}
Possibility 3:
lengthy sumTwoSmallestNumbers(std::vector<int> numbers) {
std::kind(numbers.start(), numbers.finish());
return (lengthy lengthy)numbers.at(0) + numbers.at(1);
}
#embody <algorithm>
#embody <climits>
#embody <cstdio>
#embody <random>
#embody <vector>
Describe(Assessments)
{
It(BasicTest)
{
lengthy anticipated = 13;
lengthy precise = sumTwoSmallestNumbers({ 5, 8, 12, 19, 22 });
Assert::That(precise, Is().EqualTo(anticipated));
}
It(ExtendedTest1)
{
lengthy anticipated = 6;
lengthy precise = sumTwoSmallestNumbers({ 15, 28, 4, 2, 43 });
Assert::That(precise, Is().EqualTo(anticipated));
}
It(ExtendedTest2)
{
lengthy anticipated = 10;
lengthy precise = sumTwoSmallestNumbers({ 3, 87, 45, 12, 7 });
Assert::That(precise, Is().EqualTo(anticipated));
}
It(ExtendedTest3)
{
lengthy anticipated = 4000000000;
lengthy precise = sumTwoSmallestNumbers({ 2000000000, 2000000000, 2000000000, 2000000000, 2000000000 });
Assert::That(precise, Is().EqualTo(anticipated));
}
It(ExtendedTest4)
{
lengthy anticipated = 5;
lengthy precise = sumTwoSmallestNumbers({ 1000, 2, 3 });
Assert::That(precise, Is().EqualTo(anticipated));
}
It(RandomTests)
{
auto answer = [](std::vector<int> numbers) {
std::kind(numbers.start(), numbers.finish());
return (lengthy)numbers[0] + (lengthy)numbers[1];
};
std::default_random_engine generator{std::random_device()()};
std::uniform_int_distribution<int> distributor(1, INT_MAX);
std::uniform_int_distribution<std::vector<int>::size_type> sizeDistribution(4, 20);
for(int i = 0; i < 100; i++) {
int size = sizeDistribution(generator);
std::printf("Check for:n");
std::vector<int> numbers;
for(int j = 0; j < size; j++) {
int n = distributor(generator);
numbers.push_back(n);
std::printf("%d", n);
if (j != size - 1) {
std::printf(", ");
}
}
std::printf("n<hr>n");
lengthy anticipated = answer(numbers);
lengthy precise = sumTwoSmallestNumbers(numbers);
Assert::That(precise, Is().EqualTo(anticipated));
}
}
};