Last list item: Difference between revisions

1,426 bytes added ,  11 months ago
C++ entry
No edit summary
(C++ entry)
Line 601:
Two smallest: 243 + 378 = 621
Last item is 621.
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
#include <list>
 
using namespace std;
 
void PrintContainer(const auto& container)
{
cout << "[ ";
for_each(container.begin(), container.end(), [](auto item){cout << item << " ";});
cout << "]";
}
 
int main()
{
list<int> numbers{6, 81, 243, 14, 25, 49, 123, 69, 11};
 
// a lambda to remove the minimum item
auto removeMin = [](auto& container)
{
auto minIterator = min_element(container.begin(), container.end());
auto minValue = *minIterator;
container.erase(minIterator);
return minValue;
};
while(numbers.size() > 1)
{
PrintContainer(numbers);
auto minValue = removeMin(numbers);
auto nextMinValue = removeMin(numbers);
auto sum = minValue + nextMinValue;
numbers.push_back(sum);
cout << " => " << minValue << " + " << nextMinValue << " = " << sum << "\n";
}
cout << "Final list: "; PrintContainer(numbers); cout << "\n";
}
</syntaxhighlight>
{{out}}
<pre>
[ 6 81 243 14 25 49 123 69 11 ] => 6 + 11 = 17
[ 81 243 14 25 49 123 69 17 ] => 14 + 17 = 31
[ 81 243 25 49 123 69 31 ] => 25 + 31 = 56
[ 81 243 49 123 69 56 ] => 49 + 56 = 105
[ 81 243 123 69 105 ] => 69 + 81 = 150
[ 243 123 105 150 ] => 105 + 123 = 228
[ 243 150 228 ] => 150 + 228 = 378
[ 243 378 ] => 243 + 378 = 621
Final list: [ 621 ]
</pre>
 
125

edits