It is a continuation of my previous question:
Find non duplicateTriangle Triplets from a list of given numbers
After I realized triplet structure using less space than std:vector<int>
and there is a simple way to remove duplicates from the triplets list by modifying loops index I rewrote the code again. On top of that it may be impossible to write a \$O(N^2)\$ solution for a three dimensional problem in this case. There are a few additional changes also: using lambda to avoid a function call and a few direct initialization attempts instead depending on assignment operations.
#include<vector>
#include<iostream>
struct Triplet
{
int first;
int second;
int third;
};
std::vector<Triplet> findTriangleTriplets( std::vector<int>& vec_input )
{
std::vector<Triplet> triplets;
unsigned int size = vec_input.size();
for( unsigned int i=0; i < size; ++i )
{
for( unsigned int j = i; j < size; ++j )
{
for( unsigned int k = j; k < size; ++k)
{
int first ( vec_input.at( i ) );
int second ( vec_input.at( j ) );
int third ( vec_input.at( k ) );
if( [ &first, &second, &third ] {
return ( ( second + third ) > first )&&
( ( first + third ) > second )&&
( ( first + second ) > third );
}())
{
triplets.emplace_back( Triplet{ first, second, third } );
}
}
}
}
return triplets;
}
int main()
{
std::vector<int> vec_input { 2, 4, 5, };
std::vector<Triplet> triplets = findTriangleTriplets( vec_input );
for ( auto &x : triplets )
{
std::cout<<x.first<<" "<<x.second<<" "<<x.third<<"\n";
}
return 0;
}