Thursday, May 25, 2023
HomeSoftware EngineeringThe way to Sum the Two Lowest Optimistic Integers in C++

# The way to Sum the Two Lowest Optimistic Integers in C++

## The problem#

Create a operate that returns the sum of the 2 lowest optimistic numbers given an array of minimal 4 optimistic integers. No floats or non-positive integers might 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:

``````#embrace <algorithm>
#embrace <vector>

lengthy sumTwoSmallestNumbers(std::vector<int> numbers) {
std::type(numbers.start(), numbers.finish());
return (lengthy)numbers[0] + (lengthy)numbers[1];
}
``````

Possibility 2:

``````#embrace <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::type(numbers.start(), numbers.finish());
return (lengthy lengthy)numbers.at(0) + numbers.at(1);
}
``````

## Check instances to validate our answer#

``````#embrace <algorithm>
#embrace <climits>
#embrace <cstdio>
#embrace <random>
#embrace <vector>

Describe(Exams)
{
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::type(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 precise = sumTwoSmallestNumbers(numbers);
Assert::That(precise, Is().EqualTo(anticipated));
}
}
};
``````
RELATED ARTICLES